package org.tgcloud.group.service.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;
import org.tgcloud.group.DynamicHeadListener;
import org.tgcloud.group.core.*;
import org.tgcloud.group.core.ExportUtils.ExcelExportUtil;
import org.tgcloud.group.core.ExportUtils.ExcelUtils;
import org.tgcloud.group.core.WXUtils.WeiConfig;
import org.tgcloud.group.core.date.DateUtils;
import org.tgcloud.group.entity.*;
import org.tgcloud.group.repository.*;
import org.tgcloud.group.service.manager.notify.NotifyService;
import org.tgcloud.group.service.manager.process.ProcessManageService;
import org.tgcloud.group.service.manager.project.ProjectMediaRequirementsManageService;
import org.tgcloud.group.service.manager.project.ProjectStageService;
import org.tgcloud.group.service.task.ExcelPicTask;
import org.tgcloud.group.service.task.SendSubscribeMsgTask;
import org.tgcloud.group.web.controller.dto.file.GoodExportDTO;
import org.tgcloud.group.web.controller.dto.file.GoodOrderDTO;
import org.tgcloud.group.web.controller.dto.file.HotelExportDTO;
import org.tgcloud.group.web.controller.dto.file.LocalLifeExportDTO;
import org.tgcloud.group.web.controller.dto.order.*;
import org.tgcloud.group.web.controller.dto.process.ProcessToUser;
import org.tgcloud.group.web.controller.manager.process.enums.ProcessEnum;
import org.tgcloud.group.web.controller.req.order.FlagshipStoreDataReq;
import org.tgcloud.group.web.controller.req.order.OrderIdReq;
import java.util.Objects;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author: zhy
 * @create: 2023-08-14 16:50
 * @description:
 */
@Slf4j
@Service
public class OrderManagerService {

    @Autowired
    private WeiConfig weiConfig;

    @Autowired
    private MjOrderMapper orderMapper;

    @Autowired
    private MjGoodMapper goodMapper;

    @Autowired
    private MjGoodSkuMapper goodSkuMapper;

    @Autowired
    private MjNormalUserMapper normalUserMapper;

    @Autowired
    private MjProjectMapper projectMapper;

    @Autowired
    private MjOrderSendMsgMapper orderSendMsgMapper;

    @Autowired
    private SysLabelValueMapper sysLabelValueMapper;

    @Autowired
    private MjUserOrderMapper userOrderMapper;

    @Autowired
    private MjUserOrderStatusMapper mjUserOrderStatusMapper;

    @Autowired
    private MjUserOrderGoodMapper userOrderGoodMapper;

    @Autowired
    private MjOrderBlindBoxMapper orderBlindBoxMapper;

    @Autowired
    private SendSubscribeMsgTask sendSubscribeMsgTask;

    @Autowired
    private SysPermissionMapper permissionMapper;

    @Autowired
    private ExcelPicTask excelPicTask;

    @Autowired
    private MjBusinessAccountMapper businessAccountMapper;

    @Autowired
    private MjUserOrderCheckMapper userOrderCheckMapper;

    @Autowired
    private MjOrderLocalLifeMapper orderLocalLifeMapper;

    @Autowired
    private MjOrderHotelMapper mjOrderHotelMapper;

    @Autowired
    private MjOrderTimeOutRemarkMapper orderTimeOutRemarkMapper;

    @Autowired
    private LogOperateMapper logOperateMapper;

    @Autowired
    private DateUtils dateUtils;

    @Autowired
    private BusinessAccountManageService businessAccountManageService;

    @Autowired
    private MjBusinessAccountFollowMapper businessAccountFollowMapper;

    @Autowired
    private MjOrderOtherSettingMapper orderOtherSettingMapper;

    @Autowired
    private MjOrderRateRecordMapper orderRateRecordMapper;

    @Autowired
    private SysManagerUserMapper managerUserMapper;

    @Autowired
    private ProcessManageService processManageService;

    @Autowired
    private MjBusinessPersonMapper businessPersonMapper;

    @Autowired
    private ProjectMediaRequirementsManageService projectMediaRequirementsManageService;

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private ProjectUserMapper projectUserMapper;

    @Autowired
    private MjProjectStageMapper projectStageMapper;


    @Transactional
    public APPResultMessage doSendOrder(int userId, Short userType, MultipartFile file, String cateGoryIds,
                                        String brands, Integer projectId, String goods, String projectDemand){

            MjOrder mjOrder = orderMapper.selectOne(
                    new LambdaQueryWrapper<MjOrder>()
                            .eq(MjOrder::getProjectId, projectId)
                            .notIn(MjOrder::getStatus, 9, 10, 11)
                            .isNull(MjOrder::getParentId)
            );
            if(ObjectUtils.isNotNull(mjOrder)){
                mjOrder.setStatus((short) 9);
                orderMapper.updateById(mjOrder);
            }
        try {
            boolean isChangeOrderFlag = false;

            MjProject project = projectMapper.selectByPrimaryKey(projectId);
            int fileType = 1;
            if(ObjectUtils.isNotNull(project.getProjectType()) && project.getProjectType().equals("本地生活")){
                fileType = 2;
            }
//            MjOrder mjOrder = orderMapper.selectHasAddByProjectId(projectId);
//            if (mjOrder != null){
//                // 如果是确认签单后并在竞价前，那么进行更新表单操作，订单状态不进行变动。订单必须不处于拆单的情况下
//                if (mjOrder.getIsHasChild() == 1 && project.getCheckTime() != null && mjOrder.getBiddingOneEndTime() == null){
//                    isChangeOrderFlag = true;
//                    // 原本绑定的商品列表全部删除
////                    fileType = fileType == null ? 1 : fileType;
////                    if (fileType == 2){
////                        orderLocalLifeMapper.updateStatusByOrderId(mjOrder.getId(), (short) 10);
////                    }else if (fileType == 3){
////                        mjOrderHotelMapper.updateStatusByOrderId(mjOrder.getId(), (short) 10);
////                    }else {
////                        goodMapper.updateStatusByOrderId(mjOrder.getId(), (short) 10);
////                    }
//                }
//                if (!isChangeOrderFlag){
//                    return new APPResultMessage(6001, "该项目已存在表单，请对该表单进行作废或者删除处理后再进行上传");
//                }
//            }
            String key = RedisUtil.getCacheObject("file_name_user_" + userId);
            if (StringUtil.isBlank(key)){
                key = StringUtil.generateOrderIdByName("CHECK");
            }
            excelPicTask.doDelRedisAddFile(key);
            MjProjectStage mjProjectStage = new MjProjectStage();
            mjProjectStage.setProjectId(projectId);
            mjProjectStage.setName(ProjectStatusEnum.WAIT_SELECTION_PRICING.getName());
            mjProjectStage.setCode(ProjectStatusEnum.WAIT_SELECTION_PRICING.getCode());
            MjProjectStage currentStage = projectStageMapper.selectOne(new LambdaQueryWrapper<MjProjectStage>().eq(MjProjectStage::getProjectId, projectId)
                    .eq(MjProjectStage::getIsCurrent, 1));
            mjProjectStage.setSort(currentStage.getSort() + 1);
            if (ObjectUtil.isNotNull(currentStage) && currentStage.getCode().equals(ProjectStatusEnum.WAIT_SELECTION_PRICING.getCode())){
                ResultMessage resultMessage = ResultMessage.builder();
                APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
                successMessage.setResult(resultMessage);
                return successMessage;
            }else {
                currentStage.setEndTime(new Date());
                currentStage.setIsCurrent(false);
                projectStageMapper.updateById(currentStage);
                mjProjectStage.setStartTime(new Date());
                mjProjectStage.setIsCurrent(true);
                mjProjectStage.setCreateTime(new Date());
                projectStageMapper.insert(mjProjectStage);
            }
            MjOrder order = new MjOrder();
            order.setOrderKey(key);
            order.setCreateUserId(userId);
            order.setCreateTime(new Date());
            order.setStatus((short) 2);
            order.setStageId(
                    (order.getStageId() == null || order.getStageId().trim().isEmpty())
                            ? String.valueOf(mjProjectStage.getId())
                            : Stream.concat(
                                    Arrays.stream(order.getStageId().split(",")).map(String::trim),
                                    Stream.of(String.valueOf(mjProjectStage.getId()))
                            )
                            .filter(s -> !s.isEmpty())
                            .distinct()
                            .collect(Collectors.joining(","))
            );

            order.setUpdateTime(new Date());
            order.setBrands(StringUtil.isNotBlank(brands) ? brands : project.getBrands());
            order.setCategoryId(StringUtil.isNotBlank(cateGoryIds) ? cateGoryIds : project.getCateIds());
            //当订单类型为入驻，订单状态为一次竞价中
//            if (ObjUtil.isNotNull(fileType) && fileType == 4){
//                List<MjNormalUser> users = normalUserMapper.selectListByUserType((short) 2);
//                List<Integer> idList = new ArrayList<>();
//                idList = users.stream().map(MjNormalUser::getId).collect(Collectors.toList());
//                String idsString = idList.stream()
//                        .map(String::valueOf)
//                        .collect(Collectors.joining(","));
//                order.setPushUserIds(idsString);
//                order.setStatus((short) 4);
//            } else {
//                order.setStatus((short) 2);
//            }
            order.setProjectId(projectId);
            order.setIsPush((short) 1);
            order.setIsNextPush((short) 1);
            order.setNextPushUserIds(null);
            order.setIsBlindBox((short) 1);
            order.setIsBackPush((short) 1);
            order.setFileType(fileType);
            order.setIsTimeOut((short) 1);
            order.setIsHasChild((short) 1);
            order.setIsReset((short) 1);
            order.setPushSureCheckType((short) 1);
            if (isChangeOrderFlag){
                order = mjOrder;
            }else{
                orderMapper.insert(order);
            }
            doAddGood(order, file, goods, fileType, projectId);
            //当订单类型为入驻，项目状态为已签单
            if (!isChangeOrderFlag){
                if (ObjUtil.isNotNull(fileType) && fileType == 4){
                    projectMapper.updateStatusById(project.getId(), (short) 4);
                } else {
                    projectMapper.updateStatusById(project.getId(), (short) 1);
                }
                MjBusinessAccount mjBusinessAccount = businessAccountMapper.selectHasAddById(project.getBrandId());
                if (mjBusinessAccount != null){
                    // 查询出该品牌下的所有项目，如果是执行完成的订单，则查询执行完成时间。
                    // 如果执行完成时间加上6个月比新表单所延续的时间大，则状态还是执行完成的时间
                    Integer useType = 1;
                    if (mjBusinessAccount.getStatus() != 3 || mjBusinessAccount.getStatus() != 4){
                        useType = null;
                    }
                    if (fileType == 2 || fileType == 3){
                        BusinessProjectDTO mjProjectDTO = businessAccountManageService.getMatchOrderLocalByBusinessAccountId(mjBusinessAccount.getId(), useType);
                        if (mjProjectDTO != null){
                            if (mjBusinessAccount.getStatus() != 4){
                                if (mjProjectDTO.getBusinessType() == 2){
                                    // 修改为新表单的状态
                                    Date createTime = mjProjectDTO.getCreateTime();
                                    mjBusinessAccount.setOrderTime(createTime);
                                    mjBusinessAccount.setStatus((short) 3);
                                    mjBusinessAccount.setBeginTime(createTime);
                                    String sysValue34 = sysLabelValueMapper.selectValueBySysIdAndReadOne(53);
                                    Integer i = Integer.valueOf(sysValue34);
                                    Date bTime = DateUtil.getChooseDate(createTime, 1, i);
                                    mjBusinessAccount.setEndTime(bTime);
                                    businessAccountMapper.updateByPrimaryKeySelective(mjBusinessAccount);
                                }
                            }
                        }else {
                            mjBusinessAccount.setOrderTime(new Date());
                            mjBusinessAccount.setStatus((short) 3);
                            mjBusinessAccount.setBeginTime(new Date());
                            String sysValue34 = sysLabelValueMapper.selectValueBySysIdAndReadOne(53);
                            Integer i = Integer.valueOf(sysValue34);
                            Date bTime = DateUtil.getChooseDate(new Date(), 1, i);
                            mjBusinessAccount.setEndTime(bTime);
                            businessAccountMapper.updateByPrimaryKeySelective(mjBusinessAccount);
                        }
                    }else {
                        BusinessProjectDTO mjProjectDTO = businessAccountManageService.getMatchOrderByBusinessAccountId(mjBusinessAccount.getId(), useType);
                        if (mjProjectDTO != null){
                            if (mjBusinessAccount.getStatus() != 4){
                                if (mjProjectDTO.getBusinessType() == 2){
                                    // 修改为新表单的状态
                                    Date createTime = mjProjectDTO.getCreateTime();
                                    mjBusinessAccount.setOrderTime(createTime);
                                    mjBusinessAccount.setStatus((short) 3);
                                    mjBusinessAccount.setBeginTime(createTime);
                                    String sysValue34 = sysLabelValueMapper.selectValueBySysIdAndReadOne(34);
                                    Integer i = Integer.valueOf(sysValue34);
                                    Date bTime = DateUtil.getChooseDate(createTime, 1, i);
                                    mjBusinessAccount.setEndTime(bTime);
                                    businessAccountMapper.updateByPrimaryKeySelective(mjBusinessAccount);
                                }
                            }
                        }else {
                            mjBusinessAccount.setOrderTime(new Date());
                            mjBusinessAccount.setStatus((short) 3);
                            mjBusinessAccount.setBeginTime(new Date());
                            String sysValue34 = sysLabelValueMapper.selectValueBySysIdAndReadOne(34);
                            Integer i = Integer.valueOf(sysValue34);
                            Date bTime = DateUtil.getChooseDate(new Date(), 1, i);
                            mjBusinessAccount.setEndTime(bTime);
                            businessAccountMapper.updateByPrimaryKeySelective(mjBusinessAccount);
                        }
                    }
                }
                //当订单类型为入驻，所有开拓者状态为已签单
                if (ObjUtil.isNotNull(fileType) && fileType == 4){
                    List<MjNormalUser> users = normalUserMapper.selectListByUserType((short) 2);
                    List<Integer> idList = new ArrayList<>();
                    idList = users.stream().map(MjNormalUser::getId).collect(Collectors.toList());
                    for (Integer pushUserId : idList) {
                        MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, order.getId());
                        if (isHaveObj != null){
                            MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                            orderStatusObj.setOrderStatus(85);
                            orderStatusObj.setUpdateTime(new Date());
                            orderStatusObj.setId(isHaveObj.getId());
                            mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                        } else {
                            MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                            orderStatusObj.setUserId(pushUserId);
                            orderStatusObj.setOrderId(order.getId());
                            orderStatusObj.setOrderStatus(85);
                            orderStatusObj.setCreateTime(new Date());
                            orderStatusObj.setStatus((short)1);
                            orderStatusObj.setIsNextPush((short)1);
                            mjUserOrderStatusMapper.insertSelective(orderStatusObj);
                        }
                    }
                }
            }
            if (StringUtil.isNotBlank(projectDemand)){
                // 添加项目需求
                projectMapper.updateDemandById(project.getId(), projectDemand);
            }

            projectMediaRequirementsManageService.doUpdateOrderResourcesRemarkByProjectId(project.getId());

            // 通知
            Map<String, Object> templateParams = new HashMap<>();
            notifyService.doSendNotifyByRoleId(userId, userType, "addOrder", templateParams, project.getId());

            // 推送
            MjOrder orderMsg = orderMapper.selectByPrimaryKey(order.getId());
            String roleIds = "56,65";
            String[] roleIdsList = roleIds.split(",");
            List<ProjectUser> projectUsers = projectUserMapper.selectListByProjectIdAndRoleId(roleIdsList, projectId);
            if (!BeanUtil.isNullList(projectUsers)){
                List<Integer> pushIdList = new ArrayList<>();
                for (ProjectUser projectUser : projectUsers){
                    SysManagerUser managerUser = managerUserMapper.selectByPrimaryKey(projectUser.getUserId());
                    pushIdList.add(managerUser.getBindUserId());

                }
                String pushUserIds = pushIdList.stream()
                        .map(String::valueOf) // 将每个Integer转为字符串
                        // 用逗号拼接所有userId
                        .collect(Collectors.joining(","));
                doPushOrderMsg(userId, order.getId(), pushUserIds, orderMsg.getResourcesRemark());
            }

            ResultMessage resultMessage = ResultMessage.builder().setData(order.getId());
            APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
            successMessage.setResult(resultMessage);
            return successMessage;
        } catch (Exception e){
            log.error("上传表单报错=======", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new APPResultMessage(5001, e.getMessage());
        }
    }

    public void doAddGood(MjOrder order, MultipartFile file, String goodsString, Integer fileType,Integer projectId) throws Exception{
        String fileName = StringUtil.generateOrderIdByName("CHECK");
        fileType = fileType == null ? 1 : fileType;
        if (fileType == 2){
            List<LocalLifeExportDTO> stores = new ArrayList<>();
            if (file != null){
                stores = ExcelUtils.readMultipartFile(file, LocalLifeExportDTO.class, fileName,null ,null);
            }else {
                stores = JSONObject.parseArray(goodsString, LocalLifeExportDTO.class);
            }
            Integer orderGoodNum = 0;
            BigDecimal orderGoodPrice = BigDecimal.ZERO;
            BigDecimal goodRealTotalPrice = BigDecimal.ZERO;
            for (LocalLifeExportDTO storeDto : stores) {
                MjOrderLocalLife localLife = new MjOrderLocalLife();
                localLife.setChainStoreName(storeDto.getChainStoreName());
                localLife.setNum(storeDto.getNum());
                localLife.setFinalPrice(storeDto.getFinalPrice());
                localLife.setCategory(storeDto.getCategory());
                localLife.setAverageScore(storeDto.getAverageScore());
                localLife.setCouponForm(storeDto.getCouponForm());
                localLife.setDistributedCities(storeDto.getDistributedCities());
                localLife.setCouponForm(storeDto.getCouponForm());
                localLife.setPrice(storeDto.getPrice());
                localLife.setProductName(storeDto.getProductName());
                localLife.setStoreLinks(storeDto.getStoreLinks());
                localLife.setUseRights(storeDto.getUseRights());
                localLife.setVerificationProcess(storeDto.getVerificationProcess());
                localLife.setUsageRestrictions(storeDto.getUsageRestrictions());
                localLife.setValidityPeriod(storeDto.getValidityPeriod());
                localLife.setStoreNumber(storeDto.getStoreNumber());
                localLife.setUseTime(storeDto.getUseTime());
                localLife.setSellRequirements(storeDto.getSellRequirements());
                localLife.setStatus((short) 1);
                localLife.setOrderId(order.getId());
                localLife.setCreateTime(new Date());
                try {
                    localLife.setTotalPrice(localLife.getPrice().multiply(new BigDecimal(localLife.getNum())));
                } catch (NullPointerException nullPointerException) {
                    throw new Exception("请检查数量与单价是否为空");
                }
                orderLocalLifeMapper.insertSelective(localLife);
                orderGoodNum = orderGoodNum + storeDto.getNum();
                BigDecimal oneTotalPrice = storeDto.getPrice().multiply(BigDecimal.valueOf(storeDto.getNum()));
                orderGoodPrice = orderGoodPrice.add(oneTotalPrice);
                if (storeDto.getFinalPrice() == null){
                    storeDto.setFinalPrice(BigDecimal.ZERO);
                }
                BigDecimal oneFinalTotalPrice = storeDto.getFinalPrice().multiply(BigDecimal.valueOf(storeDto.getNum()));
                goodRealTotalPrice = goodRealTotalPrice.add(oneFinalTotalPrice);
            }
            orderMapper.updateNumAndPriceByOrderId(order.getId(), orderGoodNum, orderGoodPrice, goodRealTotalPrice);
        } else if (fileType == 3){
            List<HotelExportDTO> hotels = new ArrayList<>();
            if (file != null){
                hotels = ExcelUtils.readMultipartFile(file, HotelExportDTO.class, fileName,9 ,null);
            }else {
                hotels = JSONObject.parseArray(goodsString, HotelExportDTO.class);
            }
            Integer orderGoodNum = 0;
            BigDecimal orderGoodPrice = BigDecimal.ZERO;
            BigDecimal goodRealTotalPrice = BigDecimal.ZERO;
            for (HotelExportDTO hotelDto : hotels) {
                MjOrderHotel mjOrderHotel = new MjOrderHotel();
                mjOrderHotel.setBusyTime(hotelDto.getBusyTime());
                mjOrderHotel.setHotelAddress(hotelDto.getHotelAddress());
                mjOrderHotel.setHotelPic(hotelDto.getHotelPic());
                mjOrderHotel.setHotelName(hotelDto.getHotelName());
                mjOrderHotel.setHotelType(hotelDto.getHotelType());
                mjOrderHotel.setNum(hotelDto.getNum());
                mjOrderHotel.setPrice(hotelDto.getPrice());
                mjOrderHotel.setUrl(hotelDto.getUrl());
                mjOrderHotel.setExpirationDate(hotelDto.getExpirationDate());
                mjOrderHotel.setIsHaveMorning(hotelDto.getIsHaveMorning());
                mjOrderHotel.setCreateTime(new Date());
                mjOrderHotel.setStatus((short) 1);
                mjOrderHotel.setOrderId(order.getId());
                mjOrderHotel.setRealPrice(hotelDto.getRealPrice());
                try {
                    mjOrderHotel.setTotalPrice(mjOrderHotel.getPrice().multiply(new BigDecimal(mjOrderHotel.getNum())));
                }catch (NullPointerException nullPointerException){
                    throw new Exception("请检查数量与单价是否为空");
                }
                mjOrderHotelMapper.insertSelective(mjOrderHotel);
                orderGoodNum = orderGoodNum + hotelDto.getNum();
                BigDecimal oneTotalPrice = hotelDto.getPrice().multiply(BigDecimal.valueOf(hotelDto.getNum()));
                orderGoodPrice = orderGoodPrice.add(oneTotalPrice);
                if (hotelDto.getRealPrice() == null){
                    hotelDto.setRealPrice(BigDecimal.ZERO);
                }
                BigDecimal oneFinalTotalPrice = hotelDto.getRealPrice().multiply(BigDecimal.valueOf(hotelDto.getNum()));
                goodRealTotalPrice = goodRealTotalPrice.add(oneFinalTotalPrice);
            }
            orderMapper.updateNumAndPriceByOrderId(order.getId(), orderGoodNum, orderGoodPrice, goodRealTotalPrice);
        } else {
            List<GoodExportDTO> goods = new ArrayList<>();
            if (file != null){
                goods = ExcelUtils.readMultipartFile(file, GoodExportDTO.class, fileName,8,1);
            }else {
                goods = JSONObject.parseArray(goodsString, GoodExportDTO.class);
            }
            Integer orderGoodNum = 0;
            BigDecimal orderGoodPrice = BigDecimal.ZERO;
            BigDecimal goodRealTotalPrice = BigDecimal.ZERO;
            for (GoodExportDTO goodDTO : goods) {
                MjGood mjGood = new MjGood();
                mjGood.setGoodName(goodDTO.getGoodName());
                mjGood.setGoodExpirationDate(goodDTO.getExpirationDate());
                mjGood.setGoodWarrantyDate(goodDTO.getWarrantyDate());
                mjGood.setGoodOnlineLink(goodDTO.getGoodOnlineLink());
                mjGood.setGoodPrice(goodDTO.getGoodPrice());
                mjGood.setGoodPic(goodDTO.getGoodPic());
                mjGood.setGoodCategory(goodDTO.getGoodCategory());
                mjGood.setGoodBoxNum(goodDTO.getGoodBoxNum());
                mjGood.setGoodBoxSize(goodDTO.getGoodBoxSize());
                mjGood.setGoodOneSize(goodDTO.getGoodOneSize());
                mjGood.setShopFans(goodDTO.getShopFans());
                mjGood.setGoodSaleNum(goodDTO.getGoodSaleNum());
                mjGood.setFinalPrice(goodDTO.getRealReadPrice());
                mjGood.setCreateTime(new Date());
                mjGood.setStatus((short) 1);
                mjGood.setOrderId(order.getId());
                mjGood.setGoodNum(goodDTO.getGoodNum());
                mjGood.setGoodPrice(goodDTO.getGoodPrice());
                mjGood.setFinalPrice(goodDTO.getRealReadPrice());
                BigDecimal oneGoodTotalPrice = goodDTO.getGoodPrice().multiply(BigDecimal.valueOf(goodDTO.getGoodNum()));
                mjGood.setGoodTotalPrice(oneGoodTotalPrice);
                mjGood.setBrandsValue(goodDTO.getBrandsValue());
                orderGoodPrice = orderGoodPrice.add(oneGoodTotalPrice);
                orderGoodNum = orderGoodNum + goodDTO.getGoodNum();
                if (goodDTO.getRealReadPrice() == null){
                    goodDTO.setRealReadPrice(BigDecimal.ZERO);
                }
                BigDecimal oneGoodFinalTotalPrice = goodDTO.getRealReadPrice().multiply(BigDecimal.valueOf(goodDTO.getGoodNum()));
                goodRealTotalPrice = goodRealTotalPrice.add(oneGoodFinalTotalPrice);
                goodMapper.insertSelective(mjGood);
                Integer goodId = mjGood.getId();
                MjGoodSku mjGoodSku = new MjGoodSku();
                mjGoodSku.setGoodId(goodId);
                mjGoodSku.setGoodSku(StringUtil.isNotBlank(goodDTO.getGoodSkuName()) ? goodDTO.getGoodSkuName() : "无");
                mjGoodSku.setGoodSkuPrice(goodDTO.getGoodPrice());
                mjGoodSku.setGoodSkuNum(goodDTO.getGoodNum());
                mjGoodSku.setGoodSkuPic(goodDTO.getGoodPic());
                mjGoodSku.setRealReadPrice(goodDTO.getRealReadPrice());
                mjGoodSku.setStatus((short) 1);
                mjGoodSku.setCreateTime(new Date());
                try {
                    mjGoodSku.setGoodSkuTotalPrice(goodDTO.getGoodPrice().multiply(new BigDecimal(goodDTO.getGoodNum())));
                }catch (NullPointerException nullPointerException){
                    throw new Exception("请检查数量与单价是否为空");
                }
                goodSkuMapper.insertSelective(mjGoodSku);
            }
            orderMapper.updateNumAndPriceByOrderId(order.getId(), orderGoodNum, orderGoodPrice, goodRealTotalPrice);
        }
    }

    public APPResultMessage doImportExcel(MultipartFile file, int userId, Integer projectId){
        int fileType = 1;
        MjProject mjProject = projectMapper.selectById(projectId);
        if(ObjectUtils.isNotNull(mjProject.getProjectType()) && mjProject.getProjectType().equals("本地生活")){
            fileType = 2;
        }
        String fileName = StringUtil.generateOrderIdByName("CHECK");
        Date date = new Date();
        int hours = date.getHours();
        int minutes = date.getMinutes();
        if (hours == 23){
            if (minutes >= 45){
                APPResultMessage message = APPResultMessage.getErrorMessage("23点45分之后不能上传，请0点以后上传");
                return message;
            }
        }
        try {
            RedisUtil.setCacheObject("file_name_user_" + userId, fileName);
            APPResultMessage successMessage = null;
            if (fileType == 1){
                //核价
                List<GoodExportDTO> goods = ExcelUtils.readMultipartFile(file, GoodExportDTO.class, fileName,8,1);
                if (BeanUtil.isNullList(goods)) {
                    APPResultMessage message = APPResultMessage.getErrorMessage("无可上传的数据，请重新上传表单");
                    return message;
                }
                for (GoodExportDTO dto : goods){
                    if (dto.getGoodPrice() == null){
                        APPResultMessage message = APPResultMessage.getErrorMessage("请检查旗舰店售卖价是否为空");
                        return message;
                    }
                    if (dto.getGoodNum() == null){
                        APPResultMessage message = APPResultMessage.getErrorMessage("请检查数量是否为空");
                        return message;
                    }
                }
                excelPicTask.doAddPic(fileName, file,8);
                successMessage = APPResultMessage.getSuccessMessage();
                ResultMessage resultMessage = ResultMessage.builder().setList(goods);
                successMessage.setResult(resultMessage);
            } else if (fileType == 2){
                //本地生活
                List<LocalLifeExportDTO> stores = ExcelUtils.readMultipartFile(file, LocalLifeExportDTO.class, fileName,null ,null);
                if (BeanUtil.isNullList(stores)) {
                    APPResultMessage message = APPResultMessage.getErrorMessage("无可上传的数据，请重新上传表单");
                    return message;
                }
                for (LocalLifeExportDTO dto : stores){
                    if (dto.getPrice() == null){
                        APPResultMessage message = APPResultMessage.getErrorMessage("请检查价值是否为空");
                        return message;
                    }
                    if (dto.getNum() == null){
                        APPResultMessage message = APPResultMessage.getErrorMessage("请检查数量是否为空");
                        return message;
                    }
                }
                excelPicTask.doAddPic(fileName, file,null);
                successMessage = APPResultMessage.getSuccessMessage();
                ResultMessage resultMessage = ResultMessage.builder().setList(stores);
                successMessage.setResult(resultMessage);
            } else if (fileType == 3){
                //酒店民宿
                List<HotelExportDTO> hotels = ExcelUtils.readMultipartFile(file, HotelExportDTO.class, fileName,9 ,null);
                if (BeanUtil.isNullList(hotels)) {
                    APPResultMessage message = APPResultMessage.getErrorMessage("无可上传的数据，请重新上传表单");
                    return message;
                }
                for (HotelExportDTO dto : hotels){
                    if (dto.getPrice() == null){
                        APPResultMessage message = APPResultMessage.getErrorMessage("请检查平台价是否为空");
                        return message;
                    }
                    if (dto.getNum() == null){
                        APPResultMessage message = APPResultMessage.getErrorMessage("请检查数量是否为空");
                        return message;
                    }
                }
                excelPicTask.doAddPic(fileName, file,9);
                successMessage = APPResultMessage.getSuccessMessage();
                ResultMessage resultMessage = ResultMessage.builder().setList(hotels);
                successMessage.setResult(resultMessage);
            }
            return successMessage;
        }catch (NumberFormatException e){
            log.error(e.getMessage());
            e.printStackTrace();
            return APPResultMessage.getErrorMessage(e.getMessage());
        }catch (Exception e){
            log.error(e.getMessage());
            e.printStackTrace();
            return APPResultMessage.getErrorMessage(e.getMessage());
        }finally {
            // 缓存文件名，如果到第二天凌晨，则删除缓存
            String key = "del_file_name_list:" + DateUtil.getyyyyMMddToRedis(new Date());
            String putName = fileName;
            String fileShowName = ExcelUtils.getFileName(file);
            if (fileShowName.endsWith("xls")) {
                putName = putName + ".xls";
            } else if (fileShowName.endsWith("xlsx")) {
                putName = putName + ".xlsx";
            }
            String url = ExcelUtils.doViewFilePath(GlobalStatic.downloadPath) + File.separator + putName;
            RedisUtil.setCacheObject(key + ":" + putName, url);
        }
    }

    public APPResultMessage doUpdateOrderBrand(int userId, Integer orderId, String cateGoryIds, String brands) {
        orderMapper.updateCateAndBrandByOrderId(orderId,cateGoryIds,brands);
        return APPResultMessage.getSuccessMessage();
    }
    public void exportOrder(Integer id, HttpServletResponse response) {
        // 查询订单
        MjOrder mjOrder = orderMapper.selectOne(
                new LambdaQueryWrapper<MjOrder>()
                        .eq(MjOrder::getProjectId, id)
                        .notIn(MjOrder::getStatus, 9, 10, 11)
                        .isNull(MjOrder::getParentId)
        );
        if (mjOrder == null) {
            throw new RuntimeException("订单不存在或状态不合法");
        }

        List<List<String>> headerList = new ArrayList<>();
        List<Map<String, Object>> rawDataList = new ArrayList<>();

        // 根据文件类型选择不同分支
        if (mjOrder.getFileType() == 2) {
            headerList = getLocalLifeHeader();
            List<MjOrderLocalLife> list = orderLocalLifeMapper.selectListByOrderId(mjOrder.getId());
            if (list == null) list = Collections.emptyList();
            for (MjOrderLocalLife item : list) {
                Map<String, Object> row = new LinkedHashMap<>();
                // 字段赋值，三元表达式判断 null
                row.put("id", item.getId() != null ? item.getId() : "");
                row.put("连锁店铺名称", item.getChainStoreName() != null ? item.getChainStoreName() : "");
                row.put("类别", item.getCategory() != null ? item.getCategory() : "");
                row.put("店铺数量", item.getStoreNumber() != null ? item.getStoreNumber() : "");
                row.put("美团/大众点评/小程序店铺链接", item.getLinks() != null ? item.getLinks() : "");
                row.put("美团/大众点评店铺平均评分", item.getAverageScore() != null ? item.getAverageScore() : "");
                row.put("有效期", item.getValidityPeriod() != null ? item.getValidityPeriod() : "");
                row.put("使用时间", item.getUseTime() != null ? item.getUseTime() : "");
                row.put("可使用分布城市", item.getDistributedCities() != null ? item.getDistributedCities() : "");
                row.put("产品名称", item.getProductName() != null ? item.getProductName() : "");
                row.put("套餐详细内容", item.getPackageDetails() != null ? item.getPackageDetails() : "");
                row.put("单价", item.getPrice() != null ? item.getPrice() : BigDecimal.ZERO);
                row.put("数量", item.getNum() != null ? item.getNum() : 0);
                row.put("合计货值", item.getTotalGoodPrice() != null ? item.getTotalGoodPrice() : "");
                row.put("使用权益", item.getUseRights() != null ? item.getUseRights() : "");
                row.put("卡券形式（电子/实体）", item.getCouponForm() != null ? item.getCouponForm() : "");
                row.put("使用限制", item.getUsageRestrictions() != null ? item.getUsageRestrictions() : "");
                row.put("客户对我司售卖要求", item.getSellRequirements() != null ? item.getSellRequirements() : "");
                row.put("产品/套餐链接（美团、大众点评等）", item.getStoreLinks() != null ? item.getStoreLinks() : "");
                row.put("产品/套餐图片", item.getStorePics() != null ? item.getStorePics() : "");
                row.put("产品/套餐销量（美团、大众点评）", item.getStoreSaleNumbers() != null ? item.getStoreSaleNumbers() : "");
                row.put("核销流程", item.getVerificationProcess() != null ? item.getVerificationProcess() : "");
                row.put("实际成交价", item.getFinalPrice() != null ? item.getFinalPrice() : BigDecimal.ZERO);
                row.put("旗舰店实际成交价", item.getFinalPrice() != null ? item.getFinalPrice() : BigDecimal.ZERO);
                row.put("旗舰店价格", item.getFlagshipStorePrice() != null ? item.getFlagshipStorePrice() : "");
                row.put("旗舰店粉丝量", item.getFlagshipStoreFans() != null ? item.getFlagshipStoreFans() : "");
                row.put("销量", item.getSalesNum() != null ? item.getSalesNum() : "");
                row.put("评价", item.getEvaluateContent() != null ? item.getEvaluateContent() : "");
                row.put("最低价", item.getLowestPrice() != null ? item.getLowestPrice() : "");
                row.put("链接", item.getLink() != null ? item.getLink() : "");
                rawDataList.add(row);
            }

        } else if (mjOrder.getFileType() == 3) {
            headerList = getHotelHeader();
            List<MjOrderHotel> list = mjOrderHotelMapper.selectListByOrderId(mjOrder.getId());
            if (list == null) list = Collections.emptyList();
            for (MjOrderHotel item : list) {
                Map<String, Object> row = new LinkedHashMap<>();
                // 根据你酒店实体中的字段，依样填充 row
                row.put("酒店名称", item.getHotelName() != null ? item.getHotelName() : "");
                // …其他字段
                row.put("实际成交价", item.getRealPrice() != null ? item.getRealPrice() : BigDecimal.ZERO);
                rawDataList.add(row);
            }

        } else {
            headerList = getGoodsHeader();
            List<GoodListDTO> list = goodSkuMapper.selectListByOrderId(mjOrder.getId());
            if (list == null) list = Collections.emptyList();
            for (GoodListDTO item : list) {
                Map<String, Object> row = new LinkedHashMap<>();
                row.put("id", item.getGoodSkuId() != null ? item.getGoodSkuId() : "");
                row.put("品牌", item.getBrandsValue() != null ? item.getBrandsValue() : "");
                row.put("商品名称", item.getGoodName() != null ? item.getGoodName() : "");
                row.put("有效期至", item.getGoodExpirationDate() != null ? item.getGoodExpirationDate() : "");
                row.put("保质期", item.getGoodWarrantyDate() != null ? item.getGoodWarrantyDate() : "");
                row.put("数量", item.getGoodSkuNum() != null ? item.getGoodSkuNum() : 0);
                row.put("旗舰店售卖价", item.getGoodPrice() != null ? item.getGoodPrice() : BigDecimal.ZERO);
                row.put("商品所属类别（例:妆字号、械字号、消字号、药字号等）",
                        item.getGoodCategory() != null ? item.getGoodCategory() : "");
                row.put("天猫/京东链接", item.getGoodOnlineLink() != null ? item.getGoodOnlineLink() : "");
                row.put("图片", item.getGoodPic() != null ? item.getGoodPic() : "");
                row.put("箱规（数量）", item.getGoodBoxNum() != null ? item.getGoodBoxNum() : "");
                row.put("箱规（尺寸mm）", item.getGoodBoxSize() != null ? item.getGoodBoxSize() : "");
                row.put("单个产品包装尺寸mm", item.getGoodOneSize() != null ? item.getGoodOneSize() : "");
                row.put("店铺粉丝量", item.getShopFans() != null ? item.getShopFans() : "");
                row.put("产品销量", item.getGoodSaleNum() != null ? item.getGoodSaleNum() : "");
                row.put("实际成交价", item.getFinalPrice() != null ? item.getFinalPrice() : BigDecimal.ZERO);
                row.put("旗舰店实际成交价", item.getFinalPrice() != null ? item.getFinalPrice() : BigDecimal.ZERO);
                row.put("旗舰店价格", item.getFlagshipStorePrice() != null ? item.getFlagshipStorePrice() : "");
                row.put("旗舰店粉丝量", item.getFlagshipStoreFans() != null ? item.getFlagshipStoreFans() : "");
                row.put("销量", item.getSalesNum() != null ? item.getSalesNum() : "");
                row.put("评价", item.getEvaluateContent() != null ? item.getEvaluateContent() : "");
                row.put("最低价", item.getLowestPrice() != null ? item.getLowestPrice() : "");
                row.put("链接", item.getLink() != null ? item.getLink() : "");
                rawDataList.add(row);
            }
        }

        // 将 Map 转为 List<List<Object>> 按 headerList 顺序
        List<List<Object>> dataRows = new ArrayList<>();
        for (Map<String, Object> map : rawDataList) {
            List<Object> rowList = new ArrayList<>();
            for (List<String> header : headerList) {
                String key = header.get(0);
                rowList.add(map.get(key));
            }
            dataRows.add(rowList);
        }

        // 导出
        try {
            ExcelExportUtil.exportObject(response, "核价模板", headerList, dataRows);
        } catch (IOException e) {
            throw new RuntimeException("Excel 导出失败", e);
        }
    }

    private String safeGet(Map<String, String> row, String key) {
        String value = row.get(key);
        return value != null ? value.trim() : "";
    }

    private Integer safeGetInt(Map<String, String> row, String key) {
        try {
            return row.get(key) == null ? null : Integer.valueOf(row.get(key).trim());
        } catch (Exception e) {
            return null;
        }
    }

    @Transactional
    public APPResultMessage importOrder(MultipartFile file, int userId, Integer projectId) throws IOException {

        MjProject mjProject = projectMapper.selectById(projectId);

        DynamicHeadListener listener = new DynamicHeadListener();

        EasyExcel.read(
                file.getInputStream(),
                listener
        ).sheet().doRead();

        List<Map<String, String>> rows = listener.getResult();
        if ("本地生活".equals(mjProject.getProjectType())) {

            List<MjOrderLocalLife> mjOrderLocalLives = new ArrayList<>();

            for (Map<String, String> row : rows) {

                MjOrderLocalLife item = new MjOrderLocalLife();

                // 读取 Excel 字段
                Integer id = Integer.valueOf(row.get("id"));
                String flagshipStorePrice = row.get("旗舰店价格");
                String flagshipStoreFans = row.get("旗舰店粉丝量");
                String salesNum = row.get("销量");
                String evaluateContent = row.get("评价");
                String lowestPrice = row.get("最低价");
                String link = row.get("链接");

                UpdateWrapper<MjGoodSku> wrapper = new UpdateWrapper<>();
                wrapper.eq("id", id);

                wrapper.set(flagshipStorePrice != null, "flagship_store_price", flagshipStorePrice);
                wrapper.set(flagshipStoreFans != null, "flagship_store_fans", flagshipStoreFans);
                wrapper.set(salesNum != null, "sales_num", salesNum);
                wrapper.set(evaluateContent != null, "evaluate_content", evaluateContent);
                wrapper.set(lowestPrice != null, "lowest_price", lowestPrice);
                wrapper.set(link != null, "link", link);

                if (wrapper.getSqlSet() != null && !wrapper.getSqlSet().isEmpty()) {
                    goodSkuMapper.update(null, wrapper);
                }

                // 如果你后续需要批量处理列表，可以添加
                // mjOrderLocalLives.add(item);

            }

        } else {

            List<MjGoodSku> goodSkus = new ArrayList<>();

            for (Map<String, String> row : rows) {

                MjGoodSku sku = new MjGoodSku();

                // 读取 Excel 字段
                Integer id = Integer.valueOf(row.get("id"));
                String flagshipStorePrice = row.get("旗舰店价格");
                String flagshipStoreFans = row.get("旗舰店粉丝量");
                String salesNum = row.get("销量");
                String evaluateContent = row.get("评价");
                String lowestPrice = row.get("最低价");
                String link = row.get("链接");

                // 赋值
                UpdateWrapper<MjGoodSku> wrapper = new UpdateWrapper<>();
                wrapper.eq("id", id);
                wrapper.set(flagshipStorePrice != null, "flagship_store_price", flagshipStorePrice);
                wrapper.set(flagshipStoreFans != null, "flagship_store_fans", flagshipStoreFans);
                wrapper.set(salesNum != null, "sales_num", salesNum);
                wrapper.set(evaluateContent != null, "evaluate_content", evaluateContent);
                wrapper.set(lowestPrice != null, "lowest_price", lowestPrice);
                wrapper.set(link != null, "link", link);

                if (wrapper.getSqlSet() != null && !wrapper.getSqlSet().isEmpty()) {
                    goodSkuMapper.update(null, wrapper);
                }
                // goodSkus.add(sku); // 如果你需要列表，启用
            }

        }



        MjOrder mjOrder = orderMapper.selectOne(
                new LambdaQueryWrapper<MjOrder>()
                        .eq(MjOrder::getProjectId, projectId)
                        .notIn(MjOrder::getStatus, 9, 10, 11)
                        .isNull(MjOrder::getParentId)
        );

        MjProjectStage projectStage = projectStageMapper.selectList(
                new LambdaQueryWrapper<MjProjectStage>()
                        .eq(MjProjectStage::getProjectId, projectId)
                        .eq(MjProjectStage::getIsCurrent,true)
        ).get(0);
        if(projectStage.getCode().equals(ProjectStatusEnum.WAIT_SELECTION_PRICING.getCode())){
            projectStage.setEndTime(new Date());
            projectStage.setIsCurrent(false);
            MjProjectStage mjProjectStage = new MjProjectStage();
            mjProjectStage.setCreateTime(new Date());
            mjProjectStage.setName(ProjectStatusEnum.WAIT_SELECTION_FEEDBACK.getName());
            mjProjectStage.setCode(ProjectStatusEnum.WAIT_SELECTION_FEEDBACK.getCode());
            mjProjectStage.setSort(projectStage.getSort() + 1);
            mjProjectStage.setProjectId(projectId);
            mjProjectStage.setIsCurrent(true);
            projectStageMapper.insert(mjProjectStage);
            MjOrder order = orderMapper.selectOne(
                    new LambdaQueryWrapper<MjOrder>()
                            .eq(MjOrder::getProjectId, projectId)
                            .notIn(MjOrder::getStatus, 9, 10, 11)
                            .isNull(MjOrder::getParentId)
            );
            order.setStageId(
                    (order.getStageId() == null || order.getStageId().trim().isEmpty())
                            ? String.valueOf(mjProjectStage.getId())
                            : Stream.concat(
                                    Arrays.stream(order.getStageId().split(",")).map(String::trim),
                                    Stream.of(String.valueOf(mjProjectStage.getId()))
                            )
                            .filter(s -> !s.isEmpty())
                            .distinct()
                            .collect(Collectors.joining(","))
            );
            orderMapper.updateById(order);
            projectStageMapper.updateById(projectStage);
        }

        return APPResultMessage.getSuccessMessage();
    }


    List<List<String>> getHotelHeader(){
        List<List<String>> headList = new ArrayList<>();
        headList.add(Arrays.asList("id"));
        headList.add(Arrays.asList("酒店名称"));
        headList.add(Arrays.asList("酒店类型"));
        headList.add(Arrays.asList("酒店数量"));
        headList.add(Arrays.asList("酒店所在城市及地址"));
        headList.add(Arrays.asList("美团/携程/小程序店铺链接"));
        headList.add(Arrays.asList("美团/携程店铺平均评分"));
        headList.add(Arrays.asList("产品销量"));
        headList.add(Arrays.asList("客户对我司售卖要求"));
        headList.add(Arrays.asList("旺季时间"));
        headList.add(Arrays.asList("使用限制"));
        headList.add(Arrays.asList("房型"));
        headList.add(Arrays.asList("使用有效期"));
        headList.add(Arrays.asList("是否含早"));
        headList.add(Arrays.asList("套餐详细内容"));
        headList.add(Arrays.asList("核销流程"));
        headList.add(Arrays.asList("数量"));
        headList.add(Arrays.asList("平台价"));
        headList.add(Arrays.asList("实际成交价"));
        headList.add(Arrays.asList("房型链接"));
        headList.add(Arrays.asList("房间图片"));
        headList.add(Arrays.asList("房值合计"));
        headList.add(Arrays.asList("使用权益"));
        headList.add(Arrays.asList("卡券形式（电子/实体）"));

        headList.add(Arrays.asList("旗舰店实际成交价"));
        headList.add(Arrays.asList("旗舰店价格）"));
        headList.add(Arrays.asList("旗舰店粉丝量"));
        headList.add(Arrays.asList("销量"));
        headList.add(Arrays.asList("评价"));
        headList.add(Arrays.asList("最低价"));
        headList.add(Arrays.asList("链接"));

        return headList;
    }

    List<List<String>> getLocalLifeHeader(){
        List<List<String>> headList = new ArrayList<>();
        headList.add(Arrays.asList("id"));
        headList.add(Arrays.asList("连锁店铺名称"));
        headList.add(Arrays.asList("类别"));
        headList.add(Arrays.asList("店铺数量"));
        headList.add(Arrays.asList("美团/大众点评/小程序店铺链接"));
        headList.add(Arrays.asList("美团/大众点评店铺平均评分"));
        headList.add(Arrays.asList("有效期"));
        headList.add(Arrays.asList("使用时间"));
        headList.add(Arrays.asList("可使用分布城市"));
        headList.add(Arrays.asList("产品名称"));
        headList.add(Arrays.asList("套餐详细内容"));
        headList.add(Arrays.asList("单价"));
        headList.add(Arrays.asList("数量"));
        headList.add(Arrays.asList("合计货值"));
        headList.add(Arrays.asList("使用权益"));
        headList.add(Arrays.asList("卡券形式（电子/实体）"));
        headList.add(Arrays.asList("使用限制"));
        headList.add(Arrays.asList("客户对我司售卖要求"));
        headList.add(Arrays.asList("产品/套餐链接（美团、大众点评等）"));
        headList.add(Arrays.asList("产品/套餐图片"));
        headList.add(Arrays.asList("产品/套餐销量（美团、大众点评）"));
        headList.add(Arrays.asList("核销流程"));
        headList.add(Arrays.asList("实际成交价"));

        headList.add(Arrays.asList("旗舰店实际成交价"));
        headList.add(Arrays.asList("旗舰店价格）"));
        headList.add(Arrays.asList("旗舰店粉丝量"));
        headList.add(Arrays.asList("销量"));
        headList.add(Arrays.asList("评价"));
        headList.add(Arrays.asList("最低价"));
        headList.add(Arrays.asList("链接"));
        return headList;
    }

    List<List<String>> getGoodsHeader(){
        List<List<String>> headList = new ArrayList<>();
        headList.add(Arrays.asList("id"));
        headList.add(Arrays.asList("品牌"));
        headList.add(Arrays.asList("商品名称"));
        headList.add(Arrays.asList("有效期至"));
        headList.add(Arrays.asList("保质期"));
        headList.add(Arrays.asList("规格"));
        headList.add(Arrays.asList("数量"));
        headList.add(Arrays.asList("旗舰店售卖价"));
        headList.add(Arrays.asList("商品所属类别（例:妆字号、械字号、消字号、药字号等）"));
        headList.add(Arrays.asList("天猫/京东链接"));
        headList.add(Arrays.asList("图片"));
        headList.add(Arrays.asList("箱规（数量）"));
        headList.add(Arrays.asList("箱规（尺寸mm）"));
        headList.add(Arrays.asList("单个产品包装尺寸mm"));
        headList.add(Arrays.asList("店铺粉丝量"));
        headList.add(Arrays.asList("产品销量"));
        headList.add(Arrays.asList("实际成交价"));

        headList.add(Arrays.asList("旗舰店实际成交价"));
        headList.add(Arrays.asList("旗舰店价格）"));
        headList.add(Arrays.asList("旗舰店粉丝量"));
        headList.add(Arrays.asList("销量"));
        headList.add(Arrays.asList("评价"));
        headList.add(Arrays.asList("最低价"));
        headList.add(Arrays.asList("链接"));
        return headList;
    }



    public APPResultMessage doPushOrderMsg(int userId, Integer orderId, String pushUserIds, String resourcesRemark) {
//        RedisUtil.setCacheObject("readOrder_" + orderId, GlobalStatic.noRead2);
        MjOrder order = orderMapper.selectByPrimaryKey(orderId);
        projectMapper.updateStatusById(order.getProjectId(), (short) 2);
        if (order.getIsPush() == 1){
            order.setIsPush((short) 2);
            order.setPushUserIds(pushUserIds);
            order.setUpdateTime(new Date());
            order.setResourcesRemark(resourcesRemark);
            order.setPushTime(new Date());
            //推送的同时将开拓者订单信息插入到userOderStatus表
            if (StringUtil.isNotBlank(pushUserIds)){
                for (String pushUserId : pushUserIds.trim().split(",")) {
                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(pushUserId), orderId);
                    if (isHaveObj != null){
                        MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                        orderStatusObj.setUpdateTime(new Date());
                        orderStatusObj.setOrderStatus(79);
                        orderStatusObj.setId(isHaveObj.getId());
                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                    } else {
                        MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                        orderStatusObj.setUserId(Integer.valueOf(pushUserId));
                        orderStatusObj.setOrderId(orderId);
                        orderStatusObj.setOrderStatus(79);
                        orderStatusObj.setStatus((short) 1);
                        orderStatusObj.setCreateTime(new Date());
                        orderStatusObj.setIsNextPush((short) 1);
                        mjUserOrderStatusMapper.insertSelective(orderStatusObj);
                    }
                }
            }
            orderMapper.updateByPrimaryKeySelective(order);
            //修改订单的用处和预计变现
            orderMapper.updateOrderUseAndExpectPrice(orderId,155,null);
//            // TODO: 2023/8/31 0031 推送给开拓者，开始核价流程
//            sendSubscribeMsgTask.doPushMap(pushUserIds, order.getOrderKey(), order.getBrands(), "待推送", "已建立新的项目订单，请尽快分配给渠道商", null);
        }
        return APPResultMessage.getSuccessMessage();
    }



    public APPResultMessage doRePushOrderMsg(int userId, Integer orderId, String pushUserIds) {
//        RedisUtil.setCacheObject("readOrder_" + orderId, GlobalStatic.noRead2);
        MjOrder order = orderMapper.selectByPrimaryKey(orderId);
        projectMapper.updateStatusById(order.getProjectId(), (short) 2);
        if (order.getIsPush() == 2 && order.getStatus() == 3){
            order.setIsPush((short) 2);
            order.setIsNextPush((short) 1);
            order.setStatus((short) 2);
            order.setUpdateTime(new Date());
            order.setIsBackPush((short) 2);
            order.setIsSubmitCheck((short) 1);
            order.setSubmitCheckUserIds("");
            order.setFirstPushChannelUserIds(order.getPushChannelUserIds());
            orderMapper.updateByPrimaryKeySelective(order);
            userOrderMapper.updateStatusByOrderIdAndUserIdAndOrderType(orderId,(short) 1,null, (short) 3);

            //重新推送，渠道不变，开拓者状态为需要重新核价，渠道为需重新核价
            Set<Integer> allPushUserIds = getAllPushUserIds(order.getPushUserIds(), order.getNextPushUserIds(), order.getTransferUserIds(),order.getBiddingPushUserIds());
            for (Integer pushUserId : allPushUserIds) {
                MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                mjUserOrderStatus.setOrderStatus(83);
                mjUserOrderStatus.setUpdateTime(new Date());
                MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, orderId);
                if (isHaveObj != null){
                    mjUserOrderStatus.setId(isHaveObj.getId());
                    mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                }
            }
            //渠道为需重新核价
            if (StringUtil.isNotBlank(order.getPushChannelUserIds())){
                for (String channelId : order.getPushChannelUserIds().split(",")) {
                    MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                    mjUserOrderStatus.setOrderStatus(73);
                    mjUserOrderStatus.setUpdateTime(new Date());
                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(channelId), orderId);
                    if (isHaveObj != null){
                        mjUserOrderStatus.setId(isHaveObj.getId());
                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                    }
                }
            }



//            orderMapper.updateNoPushUsersByOrderId(order.getId());
//            MjUserOrder mjUserOrder = userOrderMapper.selectIsHaveByOrderIdAndUserIdAndOrderType(null, orderId, (short) 1);
//            userOrderMapper.updateStatusByOrderIdAndUserIdAndOrderType(order.getId(),(short) 1, mjUserOrder.getUserId(), (short) 10);
//            userOrderGoodMapper.updateStatusByUserOrderId(mjUserOrder.getId());

            //记录操作日志
            logOperateMapper.addSelective(order.getProjectId(), orderId, userId,206,new Date(),3);
            sendSubscribeMsgTask.doPushMap(order.getPushUserIds(), order.getOrderKey(), order.getBrands(), "已退回，重新分配", "项目订单已退回，请重新核价", null);
        }
        return APPResultMessage.getSuccessMessage();
    }


    public APPResultMessage doSendOrderUpdate(int userId, MultipartFile file, String cateGoryIds, String brands, Integer orderId, String goods, Integer projectId) throws Exception{
//        RedisUtil.setCacheObject("readOrder_" + orderId, GlobalStatic.noRead2);
        MjOrder order = new MjOrder();
        order.setBrands(brands);
        order.setCategoryId(cateGoryIds);
        order.setStatus((short) 1);
        order.setId(orderId);
        order.setIsPush((short) 1);
        order.setPushUserIds(null);
        order.setProjectId(projectId);
        order.setIsNextPush((short) 1);
        order.setNextPushUserIds(null);
        order.setIsBlindBox((short) 1);
        order.setUpdateTime(new Date());
        orderMapper.updateByPrimaryKeySelective(order);
        goodMapper.updateStatusByOrderId(orderId, (short) 10);
        List<Integer> idList = goodMapper.selectIdListByOrderId(orderId);
        for (Integer id : idList){
            goodSkuMapper.updateStatusByGoodId(id, (short) 10);
        }
        doAddGood(order, file, goods, 1,projectId);
        // TODO: 2023/8/31 0031 推送给开拓者订单已修改，重新进行核价
        MjOrder order1 = orderMapper.selectByPrimaryKey(orderId);
        sendSubscribeMsgTask.doPushMap(order1.getPushUserIds(), order.getOrderKey(), order.getBrands(), "待推送", "项目订单已修改，请重新分配", null);
        return APPResultMessage.getSuccessMessage();
    }


    public APPResultMessage<Object, ManagerOrderDTO> doGetOrderList(Integer pageNum, Integer pageSize, String keyword, Date startTime, Date endTime,
                                                                  Short status, Integer userId, String roleIds, Integer projectId, Integer executionProgressId,
                                                                  Integer arrivalProgressId, Integer arrivalWarehouseId, Short isDiscount, Integer permissionId,
                                                                  Integer businessId, String areaId, String cateIds, BigDecimal startPrice, BigDecimal endPrice,
                                                                  String statuses, Short statusType, Short fileType, Short isTimeOut, Integer orderGo,
                                                                  Long pushSureCheckStartTime, Long pushSureCheckEndTime, Short showSubOrderType) {
        Integer managerUserId = null;
        if (StringUtil.isNotBlank(roleIds) && StringUtil.containsString(roleIds.split(","),"50")){
            managerUserId = userId;
        }
        // 判断是否是商务账户
        if (StringUtil.isNotBlank(roleIds) && (StringUtil.containsString(roleIds.split(","),"40") || StringUtil.containsString(roleIds.split(","),"55")) ){
            businessId = userId;
        }
        String[] statusList = null;
        if (StringUtil.isNotBlank(statuses)){
            statusList = statuses.split(",");
        }
//        List<SysDate> allHolidayDateList = dateUtils.getAllHolidayDateList();
        List<SysDate> allHolidayDateList = new ArrayList<>();
        if (pageNum != null && pageSize != null){
            PageHelper.startPage(pageNum,pageSize);
            //查出所有父订单，
            //-- 将订单分为拆单的和没有拆单的
            //-- 没有拆单的正常查询
            //-- 拆出来的订单，找到他的父订单，带上
            List<ManagerOrderDTO> dtos = orderMapper.selectListByKeyword(keyword, startTime, endTime, status, managerUserId, projectId,executionProgressId,
                    arrivalProgressId,arrivalWarehouseId,isDiscount,permissionId,businessId,areaId,cateIds, startPrice, endPrice, statusList,
                    statusType,fileType,isTimeOut,null,(short) 1,orderGo, pushSureCheckStartTime, pushSureCheckEndTime, allHolidayDateList,
                    showSubOrderType);
            PageInfo<ManagerOrderDTO> tables = new PageInfo<>(dtos);
            for (ManagerOrderDTO dto : tables.getList()){
                List<MjOrderSendMsg> msgs = orderSendMsgMapper.selectListByOrderId(dto.getId(), null);
                dto.setSendMsgUserList(msgs);
                ProjectListDTO projectDto = projectMapper.selectMsgById(dto.getProjectId());
                if (StringUtil.isNotBlank(projectDto.getAreaId())){
                    String s = sysLabelValueMapper.selectValueByIds(projectDto.getAreaId().split(","));
                    projectDto.setAreas(s);
                }
                if (StringUtil.isNotBlank(projectDto.getCateIds())){
                    String s = sysLabelValueMapper.selectValueByIds(projectDto.getCateIds().split(","));
                    projectDto.setCates(s);
                }
                dto.setProjectMsg(projectDto);
                Integer isAdjustOrder = 1;
                MjUserOrder mjUserOrder = userOrderMapper.selectIsHaveByOrderIdAndUserIdAndOrderType(null, dto.getId(), (short) 5);
                if (mjUserOrder != null){
                    isAdjustOrder = 2;
                }
                dto.setIsAdjustOrder(isAdjustOrder);
                //查询推送的人
                if (StringUtil.isNotBlank(dto.getPushUserIds())){
                    StringBuilder userNamesBuilder = new StringBuilder();
                    StringBuilder assistantNamesBuilder = new StringBuilder();

                    for (String pushUserId : dto.getPushUserIds().trim().split(",")) {
                        MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(pushUserId));
                        // 检查查询结果是否有效
                        if (mjNormalUser != null) {
                            //判断是否助理
                            if (mjNormalUser.getIsAssistant() == (short)1){
                                if (userNamesBuilder.length() > 0) {
                                    userNamesBuilder.append(",");
                                }
                                userNamesBuilder.append(mjNormalUser.getNickName());
                            } else if(mjNormalUser.getIsAssistant() == (short)2){
                                if (assistantNamesBuilder.length() > 0) {
                                    assistantNamesBuilder.append(",");
                                }
                                assistantNamesBuilder.append(mjNormalUser.getNickName());
                            }

                        }                    }

                    dto.setPushUserName(userNamesBuilder.toString());
                    dto.setPushAssistantName(assistantNamesBuilder.toString());
                }
                // 查询转移转推的开拓者
                if (dto.getIsNextPush() != null && dto.getIsNextPush() == 2 &&  StringUtil.isNotBlank(dto.getNextPushUserIds())){
                    String[] split = dto.getNextPushUserIds().split(",");
                    List<String> nextPushNames = new ArrayList<>();
                    List<String> nextPushAssistants = new ArrayList<>();

                    for (String nextPushUserId : split) {
                        MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(nextPushUserId));
                        // 检查查询结果是否有效
                        if (mjNormalUser != null) {
                            //判断是否助理
                            if (mjNormalUser.getIsAssistant() == (short)1){
                                nextPushNames.add(mjNormalUser.getNickName());
                            } else if(mjNormalUser.getIsAssistant() == (short)2){
                                nextPushAssistants.add(mjNormalUser.getNickName());
                            }

                        }
                    }
//                    List<String> userNames = normalUserMapper.selectUserNameByIds(split);
                    dto.setNextPushUserNames(nextPushNames);
                    dto.setNextPushAssistantNames(nextPushAssistants);
                }
                if (ObjUtil.isNotNull(dto.getIsHasChild()) && dto.getIsHasChild() == 2){
                    //查出子订单
                    List<ManagerOrderDTO> childList  = orderMapper.selectChildListByKeyword(keyword, startTime, endTime, status, managerUserId, projectId,executionProgressId,
                            arrivalProgressId,arrivalWarehouseId,isDiscount,permissionId,businessId,areaId,cateIds, startPrice, endPrice, statusList,
                            statusType,fileType,isTimeOut,dto.getId(),null);

                    if (CollUtil.isNotEmpty(childList)){
                        for (ManagerOrderDTO managerOrderDTO : childList) {
                            List<MjOrderSendMsg> msgss = orderSendMsgMapper.selectListByOrderId(managerOrderDTO.getId(), null);
                            managerOrderDTO.setSendMsgUserList(msgss);
                            ProjectListDTO projectDto2 = projectMapper.selectMsgById(managerOrderDTO.getProjectId());
                            if (StringUtil.isNotBlank(projectDto2.getAreaId())){
                                String s = sysLabelValueMapper.selectValueByIds(projectDto2.getAreaId().split(","));
                                projectDto2.setAreas(s);
                            }
                            if (StringUtil.isNotBlank(projectDto2.getCateIds())){
                                String s = sysLabelValueMapper.selectValueByIds(projectDto2.getCateIds().split(","));
                                projectDto2.setCates(s);
                            }
                            managerOrderDTO.setProjectMsg(projectDto2);
                            Integer isAdjustOrder2 = 1;
                            MjUserOrder mjUserOrder2 = userOrderMapper.selectIsHaveByOrderIdAndUserIdAndOrderType(null, managerOrderDTO.getId(), (short) 5);
                            if (mjUserOrder2 != null){
                                isAdjustOrder2 = 2;
                            }
                            managerOrderDTO.setIsAdjustOrder(isAdjustOrder2);
                            //查询推送的人
                            if (StringUtil.isNotBlank(managerOrderDTO.getPushUserIds())){
                                StringBuilder userNamesBuilder = new StringBuilder();
                                StringBuilder assistantNamesBuilder = new StringBuilder();

                                for (String pushUserId : managerOrderDTO.getPushUserIds().trim().split(",")) {
                                    MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(pushUserId));
                                    // 检查查询结果是否有效
                                    if (mjNormalUser != null) {
                                        //判断是否助理
                                        if (mjNormalUser.getIsAssistant() == (short)1){
                                            if (userNamesBuilder.length() > 0) {
                                                userNamesBuilder.append(",");
                                            }
                                            userNamesBuilder.append(mjNormalUser.getNickName());
                                        } else if(mjNormalUser.getIsAssistant() == (short)2){
                                            if (assistantNamesBuilder.length() > 0) {
                                                assistantNamesBuilder.append(",");
                                            }
                                            assistantNamesBuilder.append(mjNormalUser.getNickName());
                                        }

                                    }
                                }
                                managerOrderDTO.setPushUserName(userNamesBuilder.toString());
                                managerOrderDTO.setPushAssistantName(assistantNamesBuilder.toString());
                            }
                            // 查询转移转推的开拓者
                            if (managerOrderDTO.getIsNextPush() != null && managerOrderDTO.getIsNextPush() == 2 &&  StringUtil.isNotBlank(managerOrderDTO.getNextPushUserIds())){
                                String[] split = managerOrderDTO.getNextPushUserIds().split(",");
                                List<String> nextPushNames = new ArrayList<>();
                                List<String> nextPushAssistants = new ArrayList<>();

                                for (String nextPushUserId : split) {
                                    MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(nextPushUserId));
                                    // 检查查询结果是否有效
                                    if (mjNormalUser != null) {
                                        //判断是否助理
                                        if (mjNormalUser.getIsAssistant() == (short)1){
                                            nextPushNames.add(mjNormalUser.getNickName());
                                        } else if(mjNormalUser.getIsAssistant() == (short)2){
                                            nextPushAssistants.add(mjNormalUser.getNickName());
                                        }

                                    }
                                }
//                    List<String> userNames = normalUserMapper.selectUserNameByIds(split);
                                managerOrderDTO.setNextPushUserNames(nextPushNames);
                                managerOrderDTO.setNextPushAssistantNames(nextPushAssistants);
                            }
                        }
                        dto.setChildOrderList(childList);
                    }
                }
                // 倒计时计算
                if (dto.getPushUserHandleDiffTime() != null){
                    dto.setPushSureCheckDate(dto.getPushUserHandleDiffTime());
                }else {
                    if (dto.getProjectType() == 1){
                        // 正常订单，不包含小程序提交的其他订单
                        if (dto.getPushSureCheckType() != null){
                            if (dto.getPushSureCheckType() == 1 && dto.getPushTime() != null){
                                Long holidayNumByTime = dateUtils.getHolidayNumByTime(dto.getPushTime().getTime(), new Date().getTime());
                                dto.setPushSureCheckDate(holidayNumByTime);
                            }else if (dto.getPushSureCheckType() == 2 && dto.getPushSureCheckTime() != null){
                                Long holidayNumByTime = dateUtils.getHolidayNumByTime(dto.getPushTime().getTime(), dto.getPushSureCheckTime().getTime());
                                dto.setPushSureCheckDate(holidayNumByTime);
                                orderMapper.updatePushUserHandleDiffTimeById(holidayNumByTime, dto.getId());
                            }
                        }
                    }
                }
                // 评级
                if (dto.getRateId() != null){
                    OrderRateDTO rateDTO = doGetRateContent(dto.getRateId());
                    dto.setRate(rateDTO.getRate());
                    dto.setRateContent(rateDTO.getPcContent());
                }
            }
            ResultMessage result = ResultMessage.builder().setList(tables.getList()).setAllPageNumber(tables.getPages()).setCount(tables.getTotal());
            APPResultMessage<Object, ManagerOrderDTO> message = APPResultMessage.getSuccessMessage();
            message.setResult(result);
            return message;
        }else {
            List<ManagerOrderDTO> dtos = orderMapper.selectListByKeyword(keyword, startTime, endTime, status, managerUserId, projectId, executionProgressId,
                    arrivalProgressId, arrivalWarehouseId, isDiscount, permissionId, businessId, areaId, cateIds, startPrice, endPrice, statusList,
                    statusType,fileType,isTimeOut,null,(short) 1,orderGo, pushSureCheckStartTime, pushSureCheckEndTime, allHolidayDateList,
                    showSubOrderType);
            for (ManagerOrderDTO dto : dtos){
                List<GoodListDTO> goodListDTOS = goodSkuMapper.selectListByOrderId(dto.getId());
                dto.setGoodList(goodListDTOS);
                List<MjOrderSendMsg> msgs = orderSendMsgMapper.selectListByOrderId(dto.getId(), null);
                dto.setSendMsgUserList(msgs);
                ProjectListDTO projectDto = projectMapper.selectMsgById(dto.getProjectId());
                if (StringUtil.isNotBlank(projectDto.getAreaId())){
                    String s = sysLabelValueMapper.selectValueByIds(projectDto.getAreaId().split(","));
                    projectDto.setAreas(s);
                }
                if (StringUtil.isNotBlank(projectDto.getCateIds())){
                    String s = sysLabelValueMapper.selectValueByIds(projectDto.getCateIds().split(","));
                    projectDto.setCates(s);
                }
                dto.setProjectMsg(projectDto);
                Integer isAdjustOrder = 1;
                MjUserOrder mjUserOrder = userOrderMapper.selectIsHaveByOrderIdAndUserIdAndOrderType(null, dto.getId(), (short) 5);
                if (mjUserOrder != null){
                    isAdjustOrder = 2;
                }
                dto.setIsAdjustOrder(isAdjustOrder);
                //查询推送的人
                if (StringUtil.isNotBlank(dto.getPushUserIds())){
                    StringBuilder userNamesBuilder = new StringBuilder();
                    StringBuilder assistantNamesBuilder = new StringBuilder();

                    for (String pushUserId : dto.getPushUserIds().trim().split(",")) {
                        MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(pushUserId));
                        // 检查查询结果是否有效
                        if (mjNormalUser != null) {
                            //判断是否助理
                            if (mjNormalUser.getIsAssistant() == (short)1){
                                if (userNamesBuilder.length() > 0) {
                                    userNamesBuilder.append(",");
                                }
                                userNamesBuilder.append(mjNormalUser.getNickName());
                            } else if(mjNormalUser.getIsAssistant() == (short)2){
                                if (assistantNamesBuilder.length() > 0) {
                                    assistantNamesBuilder.append(",");
                                }
                                assistantNamesBuilder.append(mjNormalUser.getNickName());
                            }
                        }
                    }
                    dto.setPushUserName(userNamesBuilder.toString());
                    dto.setPushAssistantName(assistantNamesBuilder.toString());
                }
                // 查询转移转推的开拓者
                if (dto.getIsNextPush() != null && dto.getIsNextPush() == 2 &&  StringUtil.isNotBlank(dto.getNextPushUserIds())){
                    String[] split = dto.getNextPushUserIds().split(",");
                    List<String> nextPushNames = new ArrayList<>();
                    List<String> nextPushAssistants = new ArrayList<>();

                    for (String nextPushUserId : split) {
                        MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(nextPushUserId));
                        // 检查查询结果是否有效
                        if (mjNormalUser != null) {
                            //判断是否助理
                            if (mjNormalUser.getIsAssistant() == (short)1){
                                nextPushNames.add(mjNormalUser.getNickName());
                            } else if(mjNormalUser.getIsAssistant() == (short)2){
                                nextPushAssistants.add(mjNormalUser.getNickName());
                            }

                        }
                    }
//                    List<String> userNames = normalUserMapper.selectUserNameByIds(split);
                    dto.setNextPushUserNames(nextPushNames);
                    dto.setNextPushAssistantNames(nextPushAssistants);
                }
                if (ObjUtil.isNotNull(dto.getIsHasChild()) && dto.getIsHasChild() == 2){
                    List<ManagerOrderDTO> childList  = orderMapper.selectChildListByKeyword(keyword, startTime, endTime, status, managerUserId, projectId,executionProgressId,
                            arrivalProgressId,arrivalWarehouseId,isDiscount,permissionId,businessId,areaId,cateIds, startPrice, endPrice, statusList,
                            statusType,fileType,isTimeOut,dto.getId(),null);

                    if (CollUtil.isNotEmpty(childList)){
                        for (ManagerOrderDTO managerOrderDTO : childList) {
                            List<MjOrderSendMsg> msgss = orderSendMsgMapper.selectListByOrderId(managerOrderDTO.getId(), null);
                            managerOrderDTO.setSendMsgUserList(msgss);
                            ProjectListDTO projectDto2 = projectMapper.selectMsgById(managerOrderDTO.getProjectId());
                            if (StringUtil.isNotBlank(projectDto2.getAreaId())){
                                String s = sysLabelValueMapper.selectValueByIds(projectDto2.getAreaId().split(","));
                                projectDto2.setAreas(s);
                            }
                            if (StringUtil.isNotBlank(projectDto2.getCateIds())){
                                String s = sysLabelValueMapper.selectValueByIds(projectDto2.getCateIds().split(","));
                                projectDto2.setCates(s);
                            }
                            managerOrderDTO.setProjectMsg(projectDto2);
                            Integer isAdjustOrder2 = 1;
                            MjUserOrder mjUserOrder2 = userOrderMapper.selectIsHaveByOrderIdAndUserIdAndOrderType(null, managerOrderDTO.getId(), (short) 5);
                            if (mjUserOrder2 != null){
                                isAdjustOrder2 = 2;
                            }
                            managerOrderDTO.setIsAdjustOrder(isAdjustOrder2);
                            //查询推送的人
                            if (StringUtil.isNotBlank(managerOrderDTO.getPushUserIds())){
                                StringBuilder userNamesBuilder = new StringBuilder();
                                StringBuilder assistantNamesBuilder = new StringBuilder();

                                for (String pushUserId : managerOrderDTO.getPushUserIds().trim().split(",")) {
                                    MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(pushUserId));
                                    // 检查查询结果是否有效
                                    if (mjNormalUser != null) {
                                        //判断是否助理
                                        if (mjNormalUser.getIsAssistant() == (short)1){
                                            if (userNamesBuilder.length() > 0) {
                                                userNamesBuilder.append(",");
                                            }
                                            userNamesBuilder.append(mjNormalUser.getNickName());
                                        } else if(mjNormalUser.getIsAssistant() == (short)2){
                                            if (assistantNamesBuilder.length() > 0) {
                                                assistantNamesBuilder.append(",");
                                            }
                                            assistantNamesBuilder.append(mjNormalUser.getNickName());
                                        }

                                    }
                                }
                                managerOrderDTO.setPushUserName(userNamesBuilder.toString());
                                managerOrderDTO.setPushAssistantName(assistantNamesBuilder.toString());
                            }
                            // 查询转移转推的开拓者
                            if (managerOrderDTO.getIsNextPush() != null && managerOrderDTO.getIsNextPush() == 2 &&  StringUtil.isNotBlank(managerOrderDTO.getNextPushUserIds())){
                                String[] split = managerOrderDTO.getNextPushUserIds().split(",");
                                List<String> nextPushNames = new ArrayList<>();
                                List<String> nextPushAssistants = new ArrayList<>();

                                for (String nextPushUserId : split) {
                                    MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(nextPushUserId));
                                    // 检查查询结果是否有效
                                    if (mjNormalUser != null) {
                                        //判断是否助理
                                        if (mjNormalUser.getIsAssistant() == (short)1){
                                            nextPushNames.add(mjNormalUser.getNickName());
                                        } else if(mjNormalUser.getIsAssistant() == (short)2){
                                            nextPushAssistants.add(mjNormalUser.getNickName());
                                        }

                                    }
                                }
//                    List<String> userNames = normalUserMapper.selectUserNameByIds(split);
                                managerOrderDTO.setNextPushUserNames(nextPushNames);
                                managerOrderDTO.setNextPushAssistantNames(nextPushAssistants);
                            }
                        }
                        dto.setChildOrderList(childList);
                    }
                }
                // 倒计时计算
                if (dto.getPushUserHandleDiffTime() != null){
                    dto.setPushSureCheckDate(dto.getPushUserHandleDiffTime());
                }else {
                    if (dto.getProjectType() == 1){
                        // 正常订单，不包含小程序提交的其他订单
                        if (dto.getPushSureCheckType() != null){
                            if (dto.getPushSureCheckType() == 1 && dto.getPushTime() != null){
                                Long holidayNumByTime = dateUtils.getHolidayNumByTime(dto.getPushTime().getTime(), new Date().getTime());
                                dto.setPushSureCheckDate(holidayNumByTime);
                            }else if (dto.getPushSureCheckType() == 2 && dto.getPushSureCheckTime() != null){
                                Long holidayNumByTime = dateUtils.getHolidayNumByTime(dto.getPushTime().getTime(), dto.getPushSureCheckTime().getTime());
                                dto.setPushSureCheckDate(holidayNumByTime);
                                orderMapper.updatePushUserHandleDiffTimeById(holidayNumByTime, dto.getId());
                            }
                        }
                    }
                }
                // 评级
                if (dto.getRateId() != null){
                    OrderRateDTO rateDTO = doGetRateContent(dto.getRateId());
                    dto.setRate(rateDTO.getRate());
                    dto.setRateContent(rateDTO.getPcContent());
                }
            }
            ResultMessage resultMessage = ResultMessage.builder().setList(dtos);
            APPResultMessage<Object, ManagerOrderDTO> successMessage = APPResultMessage.getSuccessMessage();
            successMessage.setResult(resultMessage);
            return successMessage;
        }
    }

    public OrderRateDTO doGetRateContent(Integer rateId){
        OrderRateDTO dto = new OrderRateDTO();
        SysLabelValue sysLabelValue = sysLabelValueMapper.selectByPrimaryKey(rateId);
        dto.setRate(sysLabelValue.getSysValueName());
        if (StringUtil.isNotBlank(sysLabelValue.getDesc())){
            OrderRateDTO rateDTO = JSON.parseObject(sysLabelValue.getDesc(), OrderRateDTO.class);
            dto.setPcContent(rateDTO.getPcContent());
            dto.setAppContent(rateDTO.getAppContent());
        }
        return dto;
    }


    public APPResultMessage doCancelOrder(int userId, Short userType, String orderIds) {
        String[] split = orderIds.split(",");
        // TODO: 2023/8/31 0031 推送给开拓者通知该订单已作废
        for (String id : split){
            MjOrder order = orderMapper.selectByPrimaryKey(Integer.valueOf(id));
            List<TreeOrderListDTO> treeOrderListDTOS = orderMapper.selectChildOrder(order.getId());
            if (CollUtil.isNotEmpty(treeOrderListDTOS)){
                return new APPResultMessage(6001, "该表单不可作废，请先删除子表单");
            }
            if (ObjUtil.isNotNull(order.getParentId())){
                return new APPResultMessage(6001, "该表单为子表单，请至父表单处删除");
            }
            String pushUserIds = order.getPushUserIds();
            if (order.getIsNextPush() != null && order.getIsNextPush() == 2){
                pushUserIds = pushUserIds + ',' + order.getNextPushUserIds();
            }
            sendSubscribeMsgTask.doPushMap(pushUserIds, order.getOrderKey(), order.getBrands(), "已作废", "该项目订单已作废", null);
            if (StringUtil.isNotBlank(id)){
                //作废订单，开拓者和渠道的状态为已结束
                //开拓者
                Set<Integer> allPushUserIds = getAllPushUserIds(order.getPushUserIds(), order.getNextPushUserIds(), order.getTransferUserIds(),order.getBiddingPushUserIds());
                for (Integer pushUserId : allPushUserIds) {
                    MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                    mjUserOrderStatus.setOrderStatus(88);
                    mjUserOrderStatus.setUpdateTime(new Date());
                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, order.getId());
                    if (isHaveObj != null){
                        mjUserOrderStatus.setId(isHaveObj.getId());
                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                    }
                }
                //渠道
                Set<Integer> allChannelUserIds = getAllChannelUserIds(order.getPushChannelUserIds(), order.getBiddingPushChannelUserIds(), order.getFirstNextPushUserIds());
                for (Integer channelUserId : allChannelUserIds) {
                    MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                    mjUserOrderStatus.setOrderStatus(78);
                    mjUserOrderStatus.setUpdateTime(new Date());
                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(channelUserId, order.getId());
                    if (isHaveObj != null){
                        mjUserOrderStatus.setId(isHaveObj.getId());
                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                    }
                }
            }
            // 如果没有使用时长，那么添加使用时长
            if (order.getPushSureCheckType() == 1){
                orderMapper.updatePushSureCheckTypeById(order.getId());
                long time = order.getPushTime() != null ? order.getPushTime().getTime() : order.getCreateTime().getTime();
                Long holidayNumByTime = dateUtils.getHolidayNumByTime(time, new Date().getTime());
                orderMapper.updatePushUserHandleDiffTimeById(holidayNumByTime, order.getId());
            }
            //记录操作日志
            logOperateMapper.addSelective(order.getProjectId(), order.getId(), userId,214,new Date(),3);

            // 添加进程
//            processManageService.doAddProcess(order.getProjectId(), userId, userType, ProcessEnum.cancelOrder, null);
        }
        orderMapper.updateStatusByOrderIds(split, (short) 9);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage doDelOrder(int userId, String orderIds) {
        String[] split = orderIds.split(",");
        // TODO: 2023/8/31 0031 推送给开拓者通知该订单已删除
        for (String id : split) {
            MjOrder order = orderMapper.selectByPrimaryKey(Integer.valueOf(id));
            List<TreeOrderListDTO> treeOrderListDTOS = orderMapper.selectChildOrder(order.getId());
            if (CollUtil.isNotEmpty(treeOrderListDTOS)) {
                return new APPResultMessage(6001, "该表单不可删除，请先删除子表单");
            }
            if (ObjUtil.isNotNull(order.getParentId())) {
                return new APPResultMessage(6001, "该表单为子表单，请至父表单处删除");
            }
            String pushUserIds = order.getPushUserIds();
            if (order.getIsNextPush() != null && order.getIsNextPush() == 2) {
                pushUserIds = pushUserIds + ',' + order.getNextPushUserIds();
            }
            if (StringUtil.isNotBlank(id)) {
                //删除订单，开拓者和渠道的状态为已结束
                //开拓者
                Set<Integer> allPushUserIds = getAllPushUserIds(order.getPushUserIds(), order.getNextPushUserIds(), order.getTransferUserIds(), order.getBiddingPushUserIds());
                for (Integer pushUserId : allPushUserIds) {
                    MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                    mjUserOrderStatus.setOrderStatus(88);
                    mjUserOrderStatus.setUpdateTime(new Date());
                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, order.getId());
                    if (isHaveObj != null) {
                        mjUserOrderStatus.setId(isHaveObj.getId());
                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                    }
                }
                //渠道
                Set<Integer> allChannelUserIds = getAllChannelUserIds(order.getPushChannelUserIds(), order.getBiddingPushChannelUserIds(), order.getFirstNextPushUserIds());
                for (Integer channelUserId : allChannelUserIds) {
                    MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                    mjUserOrderStatus.setOrderStatus(78);
                    mjUserOrderStatus.setUpdateTime(new Date());
                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(channelUserId, order.getId());
                    if (isHaveObj != null) {
                        mjUserOrderStatus.setId(isHaveObj.getId());
                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                    }
                }
            }
            // 如果没有使用时长，那么添加使用时长
            if (order.getPushSureCheckType() == 1) {
                orderMapper.updatePushSureCheckTypeById(order.getId());
                long time = order.getPushTime() != null ? order.getPushTime().getTime() : order.getCreateTime().getTime();
                Long holidayNumByTime = dateUtils.getHolidayNumByTime(time, new Date().getTime());
                orderMapper.updatePushUserHandleDiffTimeById(holidayNumByTime, order.getId());
            }
            //记录操作日志
            logOperateMapper.addSelective(order.getProjectId(), order.getId(), userId, 215, new Date(), 3);

            sendSubscribeMsgTask.doPushMap(pushUserIds, order.getOrderKey(), order.getBrands(), "已删除", "该项目订单已删除", null);
        }

        orderMapper.updateStatusByOrderIds(split, (short) 10);

        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage getOrderMsg(int userId, Integer orderId, String roleIds) {
        BigDecimal orderFinalTotalPrice = BigDecimal.ZERO; // 实际总货值
        BigDecimal projectFinalTotalPrice = BigDecimal.ZERO; // 项目实际总货值
        ManagerOrderDTO dto = orderMapper.selectMsgByOrderId(orderId);
        ProjectListDTO projectDTO = projectMapper.selectOrderMsgById(dto.getProjectId());
        if (StringUtil.isNotBlank(projectDTO.getAreaId())) {
            String areaIds = projectDTO.getAreaId();
            String areaName = "";
            for (String areaId : areaIds.split(",")) {
                SysLabelValue labelValue = sysLabelValueMapper.selectByPrimaryKey(Integer.valueOf(areaId));
                areaName = areaName + labelValue.getSysValueName() + ";";
            }
            projectDTO.setAreas(areaName);
        }
        if (StringUtil.isNotBlank(projectDTO.getCateIds())){
            String cateIds = projectDTO.getCateIds();
            String name = "";
            for (String id : cateIds.split(",")){
                SysLabelValue labelValue = sysLabelValueMapper.selectByPrimaryKey(Integer.valueOf(id));
                name = name + labelValue.getSysValueName() + ";";
            }
            projectDTO.setCates(name);
        }
        dto.setProjectMsg(projectDTO);

        // 查询转移转推的开拓者
        if (dto.getIsNextPush() != null && dto.getIsNextPush() == 2 && dto.getNextPushUserIds() != null){
            String[] split = dto.getNextPushUserIds().split(",");
            List<String> userNames = normalUserMapper.selectUserNameByIds(split);
            dto.setNextPushUserNames(userNames);
        }

        //订单分类
        if (dto.getFileType() != null){
            if (dto.getFileType() == 2){
                List<MjOrderLocalLife> goodListDTOS = orderLocalLifeMapper.selectListByOrderId(dto.getId());
                for (MjOrderLocalLife item : goodListDTOS){
                    if (item.getFinalPrice() == null){
                        item.setFinalPrice(BigDecimal.ZERO);
                    }
                    BigDecimal finalPrice = new BigDecimal(item.getNum()).multiply(item.getFinalPrice());
                    orderFinalTotalPrice = orderFinalTotalPrice.add(finalPrice);
                }
                dto.setGoodList(goodListDTOS);
            } else if (dto.getFileType() == 3){
                List<MjOrderHotel> goodListDTOS = mjOrderHotelMapper.selectListByOrderId(dto.getId());
                for (MjOrderHotel item : goodListDTOS){
                    if (item.getRealPrice() == null){
                        item.setRealPrice(BigDecimal.ZERO);
                    }
                    BigDecimal finalPrice = new BigDecimal(item.getNum()).multiply(item.getRealPrice());
                    orderFinalTotalPrice = orderFinalTotalPrice.add(finalPrice);
                }
                dto.setGoodList(goodListDTOS);
            }else {
                List<GoodListDTO> goodListDTOS = goodSkuMapper.selectListByOrderId(dto.getId());
                for (GoodListDTO item : goodListDTOS){
                    if (item.getFinalPrice() == null){
                        item.setFinalPrice(BigDecimal.ZERO);
                    }
                    BigDecimal finalPrice = new BigDecimal(item.getGoodSkuNum()).multiply(item.getFinalPrice());
                    orderFinalTotalPrice = orderFinalTotalPrice.add(finalPrice);
                }
                dto.setGoodList(goodListDTOS);
            }
        }
        dto.setOrderFinalTotalPrice(orderFinalTotalPrice);
        // 获取项目中有效的父订单信息
        List<MjOrder> mjOrders = orderMapper.selectOrderNoChildListByProjectId(dto.getProjectId());
        for (MjOrder order : mjOrders){
            if (order.getFileType() != null){
                if (order.getFileType() == 2){
                    List<MjOrderLocalLife> goodListDTOS = orderLocalLifeMapper.selectListByOrderId(order.getId());
                    for (MjOrderLocalLife item : goodListDTOS){
                        if (item.getFinalPrice() == null){
                            item.setFinalPrice(BigDecimal.ZERO);
                        }
                        BigDecimal finalPrice = new BigDecimal(item.getNum()).multiply(item.getFinalPrice());
                        projectFinalTotalPrice = projectFinalTotalPrice.add(finalPrice);
                    }
                } else if (order.getFileType() == 3){
                    List<MjOrderHotel> goodListDTOS = mjOrderHotelMapper.selectListByOrderId(order.getId());
                    for (MjOrderHotel item : goodListDTOS){
                        if (item.getRealPrice() == null){
                            item.setRealPrice(BigDecimal.ZERO);
                        }
                        BigDecimal finalPrice = new BigDecimal(item.getNum()).multiply(item.getRealPrice());
                        projectFinalTotalPrice = projectFinalTotalPrice.add(finalPrice);
                    }
                }else {
                    List<GoodListDTO> goodListDTOS = goodSkuMapper.selectListByOrderId(order.getId());
                    for (GoodListDTO item : goodListDTOS){
                        if (item.getFinalPrice() == null){
                            item.setFinalPrice(BigDecimal.ZERO);
                        }
                        BigDecimal finalPrice = new BigDecimal(item.getGoodSkuNum()).multiply(item.getFinalPrice());
                        projectFinalTotalPrice = projectFinalTotalPrice.add(finalPrice);
                    }
                }
            }
        }
        dto.setProjectFinalTotalPrice(projectFinalTotalPrice);
        List<MjOrderSendMsg> msgs = orderSendMsgMapper.selectListByOrderId(dto.getId(), null);
        dto.setSendMsgUserList(msgs);
        if (dto.getStatus() > 1){
            List<ChannelUserGoodListDTO> checkOrderList = userOrderMapper.selectListByOrderIdAndOrderType(dto.getId(), (short) 1, null);
            for (ChannelUserGoodListDTO goodListDTO : checkOrderList){
                goodListDTO.setGoodPriceLists(userOrderGoodMapper.selectListByUserOrderId(goodListDTO.getUserOrderId()));
            }
            dto.setChannelUserCheckListDTOS(checkOrderList);
            // 判断是否有查看权限
            dto = doGetBiddingListByUserId(userId, dto);
        }

        //设置核价信息列表
        List<MjUserOrderCheck> userOrderCheckList = userOrderCheckMapper.selectListByUserIdAndOrderId(null, orderId,(short) 1);
        if (userOrderCheckList != null && userOrderCheckList.size() > 0){
            dto.setCheckMsgList(userOrderCheckList);
        }

        //设置助理核价信息列表
        List<MjUserOrderCheck> userOrderCheckListAssistant = userOrderCheckMapper.selectListByUserIdAndOrderId(null, orderId,(short) 2);
        if (userOrderCheckListAssistant != null && userOrderCheckListAssistant.size() > 0){
            dto.setAssistantCheckList(userOrderCheckListAssistant);
        }

        //返回商务提交的超时说明
        List<MjOrderTimeOutRemark> remarks = orderTimeOutRemarkMapper.selectByUserIdAndOrderId(null, orderId,(short)1);
        if (remarks != null && !remarks.isEmpty()){
            dto.setBusinessRemark(remarks);
        }

        //返回商开拓者、助理对超时的反馈意见
        List<MjOrderTimeOutRemark> remarks2 = orderTimeOutRemarkMapper.selectNormalUserByOrderId(null, orderId,(short)2);
        if (remarks2 != null && !remarks2.isEmpty()){
            dto.setBusinessRemarkReply(remarks2);
        }
        //返回子订单列表
        if (ObjUtil.isNotNull(dto.getIsHasChild()) && dto.getIsHasChild() == 2){
            List<ManagerOrderDTO> childList  = orderMapper.selectChildListByKeyword(null, null, null, null, null, null, null,
                    null, null, null, null, null, null, null, null, null, null,
                    null,null,null,dto.getId(),null);
            if (CollUtil.isNotEmpty(childList)){
                for (ManagerOrderDTO childDTO : childList) {
                    childDTO.setProjectMsg(projectDTO);
                    Integer isAdjustOrder2 = 1;
                    MjUserOrder mjUserOrder2 = userOrderMapper.selectIsHaveByOrderIdAndUserIdAndOrderType(null, childDTO.getId(), (short) 5);
                    if (mjUserOrder2 != null){
                        isAdjustOrder2 = 2;
                    }
                    childDTO.setIsAdjustOrder(isAdjustOrder2);
                    //查询推送的人
                    if (StringUtil.isNotBlank(childDTO.getPushUserIds())){
                        StringBuilder userNamesBuilder = new StringBuilder();
                        StringBuilder assistantNamesBuilder = new StringBuilder();

                        for (String pushUserId : childDTO.getPushUserIds().trim().split(",")) {
                            MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(pushUserId));
                            // 检查查询结果是否有效
                            if (mjNormalUser != null) {
                                //判断是否助理
                                if (mjNormalUser.getIsAssistant() == (short)1){
                                    if (userNamesBuilder.length() > 0) {
                                        userNamesBuilder.append(",");
                                    }
                                    userNamesBuilder.append(mjNormalUser.getNickName());
                                } else if(mjNormalUser.getIsAssistant() == (short)2){
                                    if (assistantNamesBuilder.length() > 0) {
                                        assistantNamesBuilder.append(",");
                                    }
                                    assistantNamesBuilder.append(mjNormalUser.getNickName());
                                }

                            }
                        }
                        childDTO.setPushUserName(userNamesBuilder.toString());
                        childDTO.setPushAssistantName(assistantNamesBuilder.toString());
                    }
                    // 查询转移转推的开拓者
                    if (childDTO.getIsNextPush() != null && childDTO.getIsNextPush() == 2 &&  StringUtil.isNotBlank(childDTO.getNextPushUserIds())){
                        String[] split = childDTO.getNextPushUserIds().split(",");
                        List<String> nextPushNames = new ArrayList<>();
                        List<String> nextPushAssistants = new ArrayList<>();

                        for (String nextPushUserId : split) {
                            MjNormalUser mjNormalUser = normalUserMapper.selectByPrimaryKey(Integer.valueOf(nextPushUserId));
                            // 检查查询结果是否有效
                            if (mjNormalUser != null) {
                                //判断是否助理
                                if (mjNormalUser.getIsAssistant() == (short)1){
                                    nextPushNames.add(mjNormalUser.getNickName());
                                } else if(mjNormalUser.getIsAssistant() == (short)2){
                                    nextPushAssistants.add(mjNormalUser.getNickName());
                                }

                            }
                        }
                        childDTO.setNextPushUserNames(nextPushNames);
                        childDTO.setNextPushAssistantNames(nextPushAssistants);
                    }
                }
                dto.setChildOrderList(childList);
            }
        }

        // 评级
        if (dto.getRateId() != null){
            OrderRateDTO rateDTO = doGetRateContent(dto.getRateId());
            dto.setRate(rateDTO.getRate());
            dto.setRateContent(rateDTO.getPcContent());
        }

        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setData(dto);
        successMessage.setResult(resultMessage);
        return successMessage;
    }


    private ManagerOrderDTO doGetBiddingListByUserId(Integer userId, ManagerOrderDTO dto){
        // 判断是否有查看权限
        String permission = "order:viewOrder";
        int r = permissionMapper.selectRoleIsPermissionByUserId(userId, permission);   //查看角色权限
        int u = permissionMapper.selectUserIsPermissionByUserId(userId, permission);   //查看用户单独设置的权限
        if (r > 0 || u > 0){
            if (dto.getStatus() > 3){
                // 第一次竞价
                List<ChannelUserGoodListDTO> orderList = userOrderMapper.selectListByOrderIdAndOrderType(dto.getId(), (short) 2, null);
                for (ChannelUserGoodListDTO goodListDTO : orderList){
                    goodListDTO.setGoodPriceLists(userOrderGoodMapper.selectListByUserOrderId(goodListDTO.getUserOrderId()));
                }
                dto.setChannelUserFirstBiddingListDTOS(orderList);
            }
            if (dto.getStatus() > 4){
                // 第二次竞价
                List<ChannelUserGoodListDTO> orderList = userOrderMapper.selectListByOrderIdAndOrderType(dto.getId(), (short) 3, null);
                for (ChannelUserGoodListDTO goodListDTO : orderList){
                    goodListDTO.setGoodPriceLists(userOrderGoodMapper.selectListByUserOrderId(goodListDTO.getUserOrderId()));
                }
                dto.setChannelUserSecondBiddingListDTOS(orderList);
            }
        }
        return dto;
    }


    public APPResultMessage doSureCheckOrder(int userId, String orderIds) {
        String[] split = orderIds.split(",");
        orderMapper.updateCheckStatusByOrderIds(split, (short) 4);
        // TODO: 2023/8/31 0031 推送给发布者初次确定的开拓者，让开拓者确定一次竞价的结束时间
        for (String id : split){
//            RedisUtil.setCacheObject("readOrder_" + id, GlobalStatic.noRead2);
            MjOrder order = orderMapper.selectByPrimaryKey(Integer.valueOf(id));
            projectMapper.updateCheckTimeById(order.getProjectId(), new Date());
            projectMapper.updateStatusById(order.getProjectId(), (short) 4);
            String pushUserIds = order.getPushUserIds();
            sendSubscribeMsgTask.doPushMap(pushUserIds, order.getOrderKey(), order.getBrands(), "已确认核价-确定第一次竞价的结束时间", "该项目订单已确认核价，请确定第一次竞价的结束时间", null);
        }
        return APPResultMessage.getSuccessMessage();
    }


    public APPResultMessage doAdjustOrder(int userId, String goods, Integer orderId, Integer biddingUserId) {
        MjOrder order = orderMapper.selectByPrimaryKey(orderId);
        if (order.getStatus() != 7){
            return new APPResultMessage(7001, "该订单未结束，不能调整订单");
        }
        List<GoodOrderDTO> goodExportDTOS = JSONObject.parseArray(goods, GoodOrderDTO.class);
        Map<String,Integer> goodNumMap = new HashMap<String,Integer>();
        Map<String,BigDecimal> goodPriceMap = new HashMap<String,BigDecimal>();
        BigDecimal totalPrice = BigDecimal.ZERO;
        if (order.getIsBlindBox() == 2){
            // 调整订单，已盲盒配包结束的订单，获取到的商品信息是参加竞价的
            if (biddingUserId == null){
                return new APPResultMessage(7002, "该订单已确认盲盒配包，请选择竞价的渠道商");
            }
            MjUserOrder userOrder = new MjUserOrder();
            userOrder.setOrderId(orderId);
            userOrder.setUserId(biddingUserId);
            userOrder.setOrderType((short) 4);
            userOrder.setTotalPrice(totalPrice);
            userOrder.setStatus((short) 1);
            userOrder.setCreateTime(new Date());
            userOrderMapper.insertSelective(userOrder);

            // 获取盲盒所有数量
            MjUserOrder mjUserOrder = userOrderMapper.selectIsHaveByOrderIdAndUserIdAndOrderType(null, orderId, (short) 5);
            if (mjUserOrder == null){
                List<MjOrderBlindBox> blindBoxes = orderBlindBoxMapper.selectGoodsByOrderId(orderId);
                for (MjOrderBlindBox box : blindBoxes){
                    String key = box.getGoodId() + "_" + box.getSkuId();
                    goodNumMap.put(key, box.getNum());
                    goodPriceMap.put(key, box.getPrice());
                }
                for (String priceKey : goodPriceMap.keySet()){
                    String[] s = priceKey.split("_");
                    Integer priceGoodId = Integer.valueOf(s[0]);
                    Integer priceSkuId = Integer.valueOf(s[1]);
                    MjGoodSku goodSku = goodSkuMapper.selectByPrimaryKey(priceSkuId);
                    goodPriceMap.put(priceKey, goodSku.getGoodSkuPrice());
                }
            }else {
                List<MjUserOrder> mjUserOrders = userOrderMapper.selectAddListByOrderIdAndOrderType(orderId, (short) 5);
                for (MjUserOrder userOrder1 : mjUserOrders){
                    List<GoodOrderDTO> dtos = userOrderGoodMapper.selectGoodListByUserOrderId(userOrder1.getId());
                    for (GoodOrderDTO dto : dtos){
                        String key = dto.getGoodId() + "_" + dto.getSkuId();
                        if (goodNumMap.containsKey(key)){
                            goodNumMap.put(key, goodNumMap.get(key) + dto.getGoodNum());
                        }else {
                            goodNumMap.put(key, dto.getGoodNum());
                        }
                        goodPriceMap.put(key, dto.getGoodPrice());
                    }
                }
            }
            for (GoodOrderDTO goodExportDTO : goodExportDTOS){
                // 用于竞价的数量
                Integer goodNum = goodExportDTO.getGoodNum();
                BigDecimal goodPrice = goodExportDTO.getGoodPrice();
                totalPrice = totalPrice.add(goodPrice.multiply(new BigDecimal(goodNum)));
                MjUserOrderGood orderGood = new MjUserOrderGood();
                orderGood.setUserOrderId(userOrder.getId());
                orderGood.setGoodId(goodExportDTO.getGoodId());
                orderGood.setSkuId(goodExportDTO.getSkuId());
                orderGood.setUnitPrice(goodExportDTO.getGoodPrice());
                orderGood.setNum(goodExportDTO.getGoodNum());
                orderGood.setCreateTime(new Date());
                orderGood.setStatus((short) 1);
                orderGood.setDiscountPrice(goodExportDTO.getGoodPrice());
                userOrderGoodMapper.insertSelective(orderGood);
                // 获取盲盒剩余数量
                String key = goodExportDTO.getGoodId() + "_" + goodExportDTO.getSkuId();
                goodNumMap.put(key, goodNumMap.get(key) - goodExportDTO.getGoodNum());
            }
            userOrderMapper.updateTotalPriceById(userOrder.getId(),totalPrice);
            userOrderMapper.updateStatusByOrderIdAndUserIdAndOrderType(orderId, (short) 5, null, (short) 10);
            //获取到剩余数量后，添加到调整订单-竞价里
            BigDecimal totalPrice2 = BigDecimal.ZERO;
            MjUserOrder userOrder2 = new MjUserOrder();
            userOrder2.setOrderId(orderId);
            userOrder2.setUserId(0);
            userOrder2.setOrderType((short) 5);
            userOrder2.setTotalPrice(totalPrice2);
            userOrder2.setStatus((short) 1);
            userOrder2.setCreateTime(new Date());
            userOrderMapper.insertSelective(userOrder2);
            for (String numKey : goodNumMap.keySet()){
                String[] s = numKey.split("_");
                Integer numGoodId = Integer.valueOf(s[0]);
                Integer numSkuId = Integer.valueOf(s[1]);
                MjUserOrderGood orderGood = new MjUserOrderGood();
                orderGood.setUserOrderId(userOrder2.getId());
                orderGood.setGoodId(numGoodId);
                orderGood.setSkuId(numSkuId);
                orderGood.setUnitPrice(goodPriceMap.get(numKey));
                orderGood.setNum(goodNumMap.get(numKey));
                orderGood.setCreateTime(new Date());
                orderGood.setStatus((short) 1);
                orderGood.setDiscountPrice(goodPriceMap.get(numKey));
                userOrderGoodMapper.insertSelective(orderGood);
                totalPrice2 = goodPriceMap.get(numKey).multiply(new BigDecimal(goodNumMap.get(numKey))).add(totalPrice2);
            }
            userOrderMapper.updateTotalPriceById(userOrder2.getId(),totalPrice2);

        }else {
            // 调整订单，已竞价结束的订单，获取到的商品信息是参加盲盒的
            MjUserOrder mjUserOrder = userOrderMapper.selectMsgByOrderIdAndOrderTypeAndRankNum(orderId, (short) 3, 1);
            if (mjUserOrder == null){
                // 如果没有数据，表示是第一次竞价就结束的订单
                mjUserOrder = userOrderMapper.selectMsgByOrderIdAndOrderTypeAndRankNum(orderId, (short) 2, 1);
            }
            // 获取已完成的总数量
            List<MjUserOrderGood> goodList = userOrderGoodMapper.selectMsgListByUserOrderId(mjUserOrder.getId());
            for (MjUserOrderGood orderGood : goodList){
                String key = orderGood.getGoodId() + "_" + orderGood.getSkuId();
                goodNumMap.put(key, orderGood.getNum());
                goodPriceMap.put(key, orderGood.getUnitPrice());
            }
            // 参加盲盒，创建调整订单-盲盒数据
            MjUserOrder userOrder = new MjUserOrder();
            userOrder.setOrderId(orderId);
            userOrder.setUserId(0);
            userOrder.setOrderType((short) 5);
            userOrder.setTotalPrice(totalPrice);
            userOrder.setStatus((short) 1);
            userOrder.setCreateTime(new Date());
            userOrderMapper.insertSelective(userOrder);
            for (GoodOrderDTO goodExportDTO : goodExportDTOS){
                // 盲盒的商品数量
                Integer goodNum = goodExportDTO.getGoodNum();
                BigDecimal goodPrice = goodExportDTO.getGoodPrice();
                totalPrice = totalPrice.add(goodPrice.multiply(new BigDecimal(goodNum)));
                MjUserOrderGood orderGood = new MjUserOrderGood();
                orderGood.setUserOrderId(userOrder.getId());
                orderGood.setGoodId(goodExportDTO.getGoodId());
                orderGood.setSkuId(goodExportDTO.getSkuId());
                orderGood.setUnitPrice(goodExportDTO.getGoodPrice());
                orderGood.setNum(goodExportDTO.getGoodNum());
                orderGood.setCreateTime(new Date());
                orderGood.setStatus((short) 1);
                orderGood.setDiscountPrice(goodExportDTO.getGoodPrice());
                userOrderGoodMapper.insertSelective(orderGood);
                // 获取剩余数量
                String key = goodExportDTO.getGoodId() + "_" + goodExportDTO.getSkuId();
                goodNumMap.put(key, goodNumMap.get(key) - goodExportDTO.getGoodNum());
            }
            userOrderMapper.updateTotalPriceById(userOrder.getId(),totalPrice);

            //获取到剩余数量后，添加到调整订单-盲盒里
            BigDecimal totalPrice2 = BigDecimal.ZERO;
            MjUserOrder userOrder2 = new MjUserOrder();
            userOrder2.setOrderId(orderId);
            userOrder2.setUserId(biddingUserId);
            userOrder2.setOrderType((short) 4);
            userOrder2.setTotalPrice(totalPrice2);
            userOrder2.setStatus((short) 1);
            userOrder2.setCreateTime(new Date());
            userOrderMapper.insertSelective(userOrder2);
            for (String numKey : goodNumMap.keySet()){
                String[] s = numKey.split("_");
                Integer numGoodId = Integer.valueOf(s[0]);
                Integer numSkuId = Integer.valueOf(s[1]);
                MjUserOrderGood orderGood = new MjUserOrderGood();
                orderGood.setUserOrderId(userOrder2.getId());
                orderGood.setGoodId(numGoodId);
                orderGood.setSkuId(numSkuId);
                orderGood.setUnitPrice(goodPriceMap.get(numKey));
                orderGood.setNum(goodNumMap.get(numKey));
                orderGood.setCreateTime(new Date());
                orderGood.setStatus((short) 1);
                orderGood.setDiscountPrice(goodPriceMap.get(numKey));
                userOrderGoodMapper.insertSelective(orderGood);
                totalPrice2 = goodPriceMap.get(numKey).multiply(new BigDecimal(goodNumMap.get(numKey))).add(totalPrice2);
            }
            userOrderMapper.updateTotalPriceById(userOrder2.getId(),totalPrice2);

        }
        return APPResultMessage.getSuccessMessage();
    }



    public APPResultMessage getOrderGoodList(int userId, Integer orderId) {
        MjOrder order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null){
            return new APPResultMessage(7000, "没有找到对应订单");
        }
        List<GoodOrderDTO> dtos = new ArrayList<>();
        if (order.getIsBlindBox() == 2){
            MjUserOrder mjUserOrder = userOrderMapper.selectIsHaveByOrderIdAndUserIdAndOrderType(null, orderId, (short) 5);
            if (mjUserOrder != null){
                dtos = userOrderGoodMapper.selectGoodListByUserOrderId(mjUserOrder.getId());
            }else {
                dtos = orderBlindBoxMapper.selectGoodListByOrderId(orderId);
            }
        }else {
            MjUserOrder mjUserOrder = userOrderMapper.selectMsgByOrderIdAndOrderTypeAndRankNum(orderId, (short) 3, 1);
            if (mjUserOrder == null){
                // 如果没有数据，表示是第一次竞价就结束的订单
                mjUserOrder = userOrderMapper.selectMsgByOrderIdAndOrderTypeAndRankNum(orderId, (short) 2, 1);
            }
            dtos = userOrderGoodMapper.selectGoodListByUserOrderId(mjUserOrder.getId());
        }
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setList(dtos);
        successMessage.setResult(resultMessage);
        return successMessage;
    }


    public APPResultMessage doEditOrderCost(int userId, Integer orderId,
                                            BigDecimal innerPrice, BigDecimal blindRealPrice, BigDecimal saleRealPrice,
                                            BigDecimal projectRealPrice,Integer orderGo,BigDecimal expectPrice,
                                            BigDecimal estimatedSelfMediaCost, BigDecimal estimatedExternalMediaCost,
                                            BigDecimal actualSelfMediaCost, BigDecimal actualExternalMediaCost) {
        MjOrder order = orderMapper.selectByPrimaryKey(orderId);
        BigDecimal estimatedCost = (estimatedExternalMediaCost != null ? estimatedExternalMediaCost : BigDecimal.ZERO).add(estimatedSelfMediaCost != null ? estimatedSelfMediaCost : BigDecimal.ZERO);
        BigDecimal actualCost = (actualExternalMediaCost != null ? actualExternalMediaCost : BigDecimal.ZERO).add(actualSelfMediaCost != null ? actualSelfMediaCost : BigDecimal.ZERO);
        orderMapper.updateCostByOrderId(orderId,estimatedCost,actualCost, innerPrice, blindRealPrice, saleRealPrice, projectRealPrice,
                estimatedSelfMediaCost, estimatedExternalMediaCost, actualSelfMediaCost, actualExternalMediaCost);
        if ((blindRealPrice != null && blindRealPrice.compareTo(BigDecimal.ZERO) > 0) || (saleRealPrice != null && saleRealPrice.compareTo(BigDecimal.ZERO) > 0)){
            projectMapper.updateStatusById(order.getProjectId(), (short) 5);
        }
        if (orderGo != null || expectPrice != null){
            if (ObjUtil.isNotNull(orderGo) && orderGo == 155){
                orderMapper.updateOrderUseAndExpectPrice(orderId,orderGo,null);
                orderMapper.resetExpectPrice(orderId);
            } else {
                orderMapper.updateOrderUseAndExpectPrice(orderId,orderGo,expectPrice);
            }
        }
        if ((innerPrice != null || actualCost != null) && order.getIsHasChild() != null && order.getIsHasChild() == 2){
            doCountSubOrder(orderId);
        }
        // 如果是子订单，并且其他竞价的订单都填写了卖货实收，那么就更新其他不是竞价的子订单里的预计变现
        if(order.getParentId() != null && (order.getExpectPrice() == null || order.getExpectPrice().compareTo(BigDecimal.ZERO) > 0)){
            doUpdateOrderExpectPrice(order.getParentId());
        }
        return APPResultMessage.getSuccessMessage();
    }

    public void doUpdateOrderExpectPrice(Integer orderId){
        // 查询出所有的子订单
        List<MjOrder> mjOrders = orderMapper.selectSubOrderByParentOrderId(orderId);
        boolean hasAddSaleRealPrice = true;
        BigDecimal saleRealPrice = BigDecimal.ZERO;
        BigDecimal saleTotalPrice = BigDecimal.ZERO;
        for (MjOrder mjOrder : mjOrders){
            if(mjOrder.getOrderGo() == 155 && (mjOrder.getSaleRealPrice() == null || mjOrder.getSaleRealPrice().compareTo(BigDecimal.ZERO) <= 0)){
                // 卖货实收为空或者小于等于0的，都不进行计算
                hasAddSaleRealPrice = false;
            }
            if (mjOrder.getOrderGo() == 155){
                saleRealPrice = saleRealPrice.add(mjOrder.getSaleRealPrice() == null ? BigDecimal.ZERO : mjOrder.getSaleRealPrice());
                saleTotalPrice = saleTotalPrice.add(mjOrder.getTotalPrice() == null ? BigDecimal.ZERO : mjOrder.getTotalPrice());
            }
        }
        if (hasAddSaleRealPrice){
            // 计算易货子订单的比例，所有订单去向为易货的子订单的卖货实收/所有订单去向为易货的子订单的订单总计
            BigDecimal saleRate = saleRealPrice.divide(saleTotalPrice, 6, BigDecimal.ROUND_HALF_UP);
            // 计算其他子订单的预计变现
            for (MjOrder mjOrder : mjOrders){
                if (!mjOrder.getOrderGo().equals(155)){
                    BigDecimal expectPrice = mjOrder.getTotalPrice().multiply(saleRate).setScale(2, BigDecimal.ROUND_HALF_UP);
                    orderMapper.updateOrderExpectPrice(mjOrder.getId(),expectPrice);
                }
            }
        }
    }

    public APPResultMessage doPushOrderResourcesRemark(int userId, Integer orderId, String resourcesRemark) {
        MjOrder order = orderMapper.selectByPrimaryKey(orderId);
        order.setResourcesRemark(resourcesRemark);
        orderMapper.updateByPrimaryKeySelective(order);
        return APPResultMessage.getSuccessMessage();
    }

    public  Set<Integer> getAllPushUserIds(String pushUserIds,String nextPushUserIds,String transferUserIds,String biddingPushUserIds) {
        Set<Integer> userIdSet= new HashSet<>();
        if (StringUtil.isNotBlank(pushUserIds)){
            List<Integer> str1 = Arrays.stream(pushUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str1);
        }

        if (StringUtil.isNotBlank(nextPushUserIds)){
            List<Integer> str2 = Arrays.stream(nextPushUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str2);
        }
        if (StringUtil.isNotBlank(transferUserIds)){
            List<Integer> str3 = Arrays.stream(transferUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str3);
        }
        if (StringUtil.isNotBlank(biddingPushUserIds)){
            List<Integer> str4 = Arrays.stream(biddingPushUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str4);
        }
        return userIdSet;
    }

    public  Set<Integer> getAllChannelUserIds(String pushChannelUserIds,String biddingPushChannelUserIds,String firstNextPushUserIds) {
        Set<Integer> userIdSet= new HashSet<>();
        if (StringUtil.isNotBlank(pushChannelUserIds)){
            List<Integer> str1 = Arrays.stream(pushChannelUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str1);
        }

        if (StringUtil.isNotBlank(biddingPushChannelUserIds)){
            List<Integer> str2 = Arrays.stream(biddingPushChannelUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str2);
        }
        if (StringUtil.isNotBlank(firstNextPushUserIds)){
            List<Integer> str3 = Arrays.stream(firstNextPushUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str3);
        }
        return userIdSet;
    }

    public APPResultMessage doAddTimeOutRemark(Integer userId, Integer orderId, String content) {
        MjOrder order = orderMapper.selectByPrimaryKey(orderId);
        if (order.getIsTimeOut() != null && order.getIsTimeOut() == 2){
            Set<Integer> allPushUserIds = getAllPushUserIds(order.getPushUserIds(), order.getNextPushUserIds(), order.getTransferUserIds(),order.getBiddingPushUserIds());
            MjOrderTimeOutRemark orderTimeOutRemark = new MjOrderTimeOutRemark();
            orderTimeOutRemark.setOrderId(orderId);
            orderTimeOutRemark.setUserId(userId);
            orderTimeOutRemark.setContent(content);
            orderTimeOutRemark.setContentType((short) 1);
            orderTimeOutRemark.setCreateTime(new Date());
            orderTimeOutRemark.setStatus(1);
            //新增记录
            orderTimeOutRemarkMapper.insertSelective(orderTimeOutRemark);
            //如果是商务的说明，改变所有开拓者和助理的状态为未签单说明
            for (Integer pushUserId : allPushUserIds) {
                //修改目标
                MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                mjUserOrderStatus.setOrderStatus(95);
                mjUserOrderStatus.setUpdateTime(new Date());
                //源对象
                MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, orderId);
                if (isHaveObj != null){
                    mjUserOrderStatus.setId(isHaveObj.getId());
                    //上一个状态不能为95，否则如果一个商务提交两次，会恢复不到原来的状态
                    if (isHaveObj.getOrderStatus() == 95 ){

                    } else {
                        mjUserOrderStatus.setPreviousStatus(isHaveObj.getOrderStatus());
                    }
                    mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                }
            }
            return APPResultMessage.getSuccessMessage();
        } else {
            return APPResultMessage.getErrorMessage("开拓者已给予反馈意见");
        }
    }


    @Transactional
    public APPResultMessage doSplitOrder(int userId, Integer parentId, String orderStr, Integer fileType, String useTypeStr) {
        MjOrder parenOrder = orderMapper.selectByPrimaryKey(parentId);
        //已经是子订单的订单，不可拆单
        if (ObjUtil.isNull(parenOrder.getParentId())){
            //盲盒配包的订单，不可以拆单
            if (ObjUtil.isNotNull(parenOrder.getIsBlindBox()) && parenOrder.getIsBlindBox() == 1){
                //只有已签单并且没有竞价的才能拆分
//            if (ObjUtil.isNotNull(parenOrder.getCheckTime()) && ObjUtil.isNull(parenOrder.getBiddingOneEndTime()) && parenOrder.getStatus() < 5){
                List<TreeOrderListDTO> treeOrderListDTOS = orderMapper.selectChildOrder(parentId);
                if (ObjUtil.isNotNull(parenOrder.getIsHasChild()) && parenOrder.getIsHasChild() != 2 && CollUtil.isEmpty(treeOrderListDTOS) ){
                    if (ObjUtil.isNotNull(fileType) && fileType == 1){
                        if (StrUtil.isNotBlank(orderStr) && StrUtil.isNotBlank(useTypeStr)){
                            Map<String, List<SplitGoodStrDTO>> orderMap = JSON.parseObject(orderStr, new TypeReference<Map<String, List<SplitGoodStrDTO>>>() {});
                            Map<String, useTypeDTO> useTypeMap = JSON.parseObject(useTypeStr, new TypeReference<Map<String, useTypeDTO>>() {});
                            Boolean hasCheckOrderFlag = false;
                            // 传的参数是一个Map的json对象，里面key为随意值，value为list<SplitGoodStrDTO>，SplitGoodStrDTO记录goodId,skuId,num
                            Integer splitTotalNum = 0;
                            //先遍历每个sku校验要拆单的商品数量和原表单商品数量是否一致
                            for (Map.Entry<String, List<SplitGoodStrDTO>> entry : orderMap.entrySet()){
                                List<SplitGoodStrDTO> goodStrList = entry.getValue();
                                for (SplitGoodStrDTO strDTO : goodStrList){
                                    splitTotalNum = splitTotalNum + strDTO.getNum();
                                }
                            }
                            if (splitTotalNum > parenOrder.getTotalNum()){
                                return new APPResultMessage(6001, "拆单商品总数量超过原表单数量");
                            } else if (splitTotalNum < parenOrder.getTotalNum()) {
                                return new APPResultMessage(6001, "拆单商品总数量小于原表单数量");
                            }
                            //遍历每个订单
                            for (Map.Entry<String, List<SplitGoodStrDTO>> entry : orderMap.entrySet()) {
                                List<SplitGoodStrDTO> goodStrList = entry.getValue();
                                if (goodStrList != null) {
                                    //目标商品总价
                                    BigDecimal targetGoodTotalPrice = BigDecimal.ZERO;
                                    //目标商品实际成交总价
                                    BigDecimal targetGoodRealTotalPrice = BigDecimal.ZERO;
                                    //目标商品总数
                                    Integer targetGoodTotalNum = 0;
                                    //order
                                    MjOrder targetOrder = new MjOrder();
                                    targetOrder.setOrderKey(parenOrder.getOrderKey() + "-" + entry.getKey());
                                    targetOrder.setCreateUserId(userId);
                                    targetOrder.setCreateTime(new Date());
                                    targetOrder.setUpdateTime(new Date());
                                    targetOrder.setBrands(parenOrder.getBrands());
                                    targetOrder.setCategoryId(parenOrder.getCategoryId());
                                    targetOrder.setProjectId(parenOrder.getProjectId());
                                    targetOrder.setIsPush(parenOrder.getIsPush());
                                    targetOrder.setPushUserIds(parenOrder.getPushUserIds());
                                    targetOrder.setIsNextPush((short) 1);
                                    targetOrder.setNextPushUserIds(null);
                                    targetOrder.setIsBlindBox((short) 1);
                                    targetOrder.setIsBackPush((short) 1);
                                    targetOrder.setFileType(fileType);
                                    targetOrder.setIsTimeOut((short) 1);
                                    targetOrder.setIsHasChild((short) 1);
                                    targetOrder.setIsReset((short) 1);
                                    targetOrder.setParentId(parentId);
                                    if (useTypeMap.containsKey(entry.getKey())){
                                        useTypeDTO useTypeDTO = useTypeMap.get(entry.getKey());
                                        if (ObjUtil.isNotNull(useTypeDTO)){
                                            targetOrder.setOrderGo(useTypeDTO.getUseType());
                                            if (useTypeDTO.getUseType() == 155){
                                                hasCheckOrderFlag = true;
                                                targetOrder.setExpectPrice(null);
                                                targetOrder.setStatus((short) 4);
                                                if (ObjUtil.isNotNull(parenOrder.getCheckTime())){
                                                    targetOrder.setCheckTime(parenOrder.getCheckTime());
                                                }
                                                orderMapper.insertSelective(targetOrder);
                                                //开拓者为已签单状态
                                                Set<Integer> allPushUserIds = getAllPushUserIds(parenOrder.getPushUserIds(), parenOrder.getNextPushUserIds(), parenOrder.getTransferUserIds(),parenOrder.getBiddingPushUserIds());
                                                for (Integer pushUserId : allPushUserIds) {
                                                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, targetOrder.getId());
                                                    if (isHaveObj != null){
                                                        MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                                        orderStatusObj.setOrderStatus(85);
                                                        orderStatusObj.setUpdateTime(new Date());
                                                        orderStatusObj.setId(isHaveObj.getId());
                                                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                                    } else {
                                                        MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                                        orderStatusObj.setUserId(pushUserId);
                                                        orderStatusObj.setOrderId(targetOrder.getId());
                                                        orderStatusObj.setOrderStatus(85);
                                                        orderStatusObj.setCreateTime(new Date());
                                                        orderStatusObj.setStatus((short)1);
                                                        orderStatusObj.setIsNextPush((short)1);
                                                        mjUserOrderStatusMapper.insertSelective(orderStatusObj);
                                                    }
                                                }
                                            } else {
                                                targetOrder.setStatus((short) 7);
                                                targetOrder.setEndTime(new Date());
                                                if (ObjUtil.isNotNull(parenOrder.getCheckTime())){
                                                    targetOrder.setCheckTime(parenOrder.getCheckTime());
                                                }
                                                targetOrder.setExpectPrice(useTypeDTO.getExpectPrice());
                                                orderMapper.insertSelective(targetOrder);
                                                if (ObjUtil.isNotNull(targetOrder.getEndTime())){
                                                    //修改父订单结束时间
                                                    orderMapper.updateEndTime(parenOrder.getId(),targetOrder.getEndTime());
                                                }
                                                //开拓者为已签单状态
                                                Set<Integer> allPushUserIds = getAllPushUserIds(parenOrder.getPushUserIds(), parenOrder.getNextPushUserIds(), parenOrder.getTransferUserIds(),parenOrder.getBiddingPushUserIds());
                                                for (Integer pushUserId : allPushUserIds) {
                                                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, targetOrder.getId());
                                                    if (isHaveObj != null){
                                                        MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                                        orderStatusObj.setOrderStatus(88);
                                                        orderStatusObj.setUpdateTime(new Date());
                                                        orderStatusObj.setId(isHaveObj.getId());
                                                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                                    } else {
                                                        MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                                        orderStatusObj.setUserId(pushUserId);
                                                        orderStatusObj.setOrderId(targetOrder.getId());
                                                        orderStatusObj.setOrderStatus(88);
                                                        orderStatusObj.setCreateTime(new Date());
                                                        orderStatusObj.setStatus((short)1);
                                                        orderStatusObj.setIsNextPush((short)1);
                                                        mjUserOrderStatusMapper.insertSelective(orderStatusObj);
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    //遍历每一个sku
                                    for (SplitGoodStrDTO strDTO : goodStrList) {
                                        if (ObjUtil.isNotNull(strDTO.getGoodId()) && strDTO.getNum() != 0){
                                            //查找原表单的good
                                            MjGood oldGood = goodMapper.selectByPrimaryKey(strDTO.getGoodId());
                                            if (ObjUtil.isNotNull(strDTO.getSkuId())){
                                                //查找原表单的sku
                                                MjGoodSku oldGoodSku = goodSkuMapper.selectByPrimaryKey(strDTO.getSkuId());
                                                if (strDTO.getNum() <= oldGoodSku.getGoodSkuNum()){
                                                    MjGood targetGood = new MjGood();
                                                    targetGood.setGoodNum(strDTO.getNum());
                                                    targetGood.setGoodName(oldGood.getGoodName());
                                                    targetGood.setGoodExpirationDate(oldGood.getGoodExpirationDate());
                                                    targetGood.setGoodWarrantyDate(oldGood.getGoodWarrantyDate());
                                                    targetGood.setGoodOnlineLink(oldGood.getGoodOnlineLink());
                                                    //价格就是总价=sku单价*数量
                                                    targetGood.setGoodPrice(oldGoodSku.getGoodSkuPrice().multiply(new BigDecimal(strDTO.getNum())));
                                                    targetGood.setGoodPic(oldGood.getGoodPic());
                                                    targetGood.setGoodCategory(oldGood.getGoodCategory());
                                                    targetGood.setGoodBoxNum(oldGood.getGoodBoxNum());
                                                    targetGood.setGoodBoxSize(oldGood.getGoodBoxSize());
                                                    targetGood.setGoodOneSize(oldGood.getGoodOneSize());
                                                    targetGood.setShopFans(oldGood.getShopFans());
                                                    targetGood.setGoodSaleNum(oldGood.getGoodSaleNum());
                                                    //实际成交价也用sku的
                                                    targetGood.setFinalPrice(oldGoodSku.getRealReadPrice() == null ? BigDecimal.ZERO :oldGoodSku.getRealReadPrice());
                                                    targetGood.setCreateTime(new Date());
                                                    targetGood.setStatus((short) 1);
                                                    targetGood.setOrderId(targetOrder.getId());
                                                    //价格就是总价=sku单价*数量
                                                    targetGood.setGoodTotalPrice(oldGoodSku.getGoodSkuPrice().multiply(new BigDecimal(strDTO.getNum())));
                                                    goodMapper.insertSelective(targetGood);

                                                    //sku
                                                    MjGoodSku targetGoodSku = new MjGoodSku();
                                                    targetGoodSku.setGoodSkuNum(strDTO.getNum());
                                                    targetGoodSku.setGoodSkuPic(oldGoodSku.getGoodSkuPic());
                                                    targetGoodSku.setGoodSkuPrice(oldGoodSku.getGoodSkuPrice());
                                                    targetGoodSku.setGoodSku(oldGoodSku.getGoodSku());
                                                    targetGoodSku.setGoodId(targetGood.getId());
                                                    targetGoodSku.setCreateTime(new Date());
                                                    targetGoodSku.setStatus((short) 1);
                                                    targetGoodSku.setRealReadPrice(oldGoodSku.getRealReadPrice() == null ? BigDecimal.ZERO : oldGoodSku.getRealReadPrice());
                                                    targetGoodSku.setGoodSkuTotalPrice(oldGoodSku.getGoodSkuPrice().multiply(new BigDecimal(strDTO.getNum())));
                                                    goodSkuMapper.insertSelective(targetGoodSku);

                                                    targetGoodTotalPrice = targetGoodTotalPrice.add(oldGoodSku.getGoodSkuPrice().multiply(new BigDecimal(strDTO.getNum())));
                                                    targetGoodRealTotalPrice = targetGoodRealTotalPrice.add(oldGoodSku.getRealReadPrice() == null ? BigDecimal.ZERO: oldGoodSku.getRealReadPrice().multiply(new BigDecimal(strDTO.getNum())));
                                                    targetGoodTotalNum = targetGoodTotalNum + strDTO.getNum();

                                                } else {
                                                    return new APPResultMessage(6001, "拆单商品: "+oldGood.getGoodName()+" 数量超过原表单数量");
                                                }
                                            }
                                        }
                                    }
                                    orderMapper.updateNumAndPriceByOrderId(targetOrder.getId(), targetGoodTotalNum, targetGoodTotalPrice, targetGoodRealTotalPrice);
                                }
                            }
                            if (!hasCheckOrderFlag){
                                //如果拆分的几个子表单，都不是走竞价的，那么整个订单结束
                                orderMapper.updateStatusByOrderId(parentId,(short) 7);
                                orderMapper.updateEndTime(parentId,new Date());
                                //开拓者为已结束状态
                                Set<Integer> allPushUserIds = getAllPushUserIds(parenOrder.getPushUserIds(), parenOrder.getNextPushUserIds(), parenOrder.getTransferUserIds(),parenOrder.getBiddingPushUserIds());
                                for (Integer pushUserId : allPushUserIds) {
                                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, parentId);
                                    if (isHaveObj != null){
                                        MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                        orderStatusObj.setOrderStatus(88);
                                        orderStatusObj.setPreviousStatus(isHaveObj.getOrderStatus());
                                        orderStatusObj.setUpdateTime(new Date());
                                        orderStatusObj.setId(isHaveObj.getId());
                                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                    }
                                }
                                //渠道为已结束状态------但是小程序渠道看不到父表单
                                if (StringUtil.isNotBlank(parenOrder.getPushChannelUserIds())){
                                    for (String channelId : parenOrder.getPushChannelUserIds().split(",")) {
                                        MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                                        mjUserOrderStatus.setOrderStatus(78);
                                        mjUserOrderStatus.setUpdateTime(new Date());
                                        MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(channelId), parentId);
                                        if (isHaveObj != null){
                                            mjUserOrderStatus.setPreviousStatus(isHaveObj.getOrderStatus());
                                            mjUserOrderStatus.setId(isHaveObj.getId());
                                            mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                                        }
                                    }
                                }
                            }
                        } else {
                            return new APPResultMessage(6001, "订单列表缺失");
                        }
                    }
                    orderMapper.updateIsHasChild(parentId,(short) 2);
                } else {
                    return new APPResultMessage(6001, "该表已有子表单，请删除已有子表单重试");
                }

                //记录操作日志
                logOperateMapper.addSelective(parenOrder.getProjectId(), parenOrder.getId(), userId,211,new Date(),3);
//            } else {
//                return new APPResultMessage(6001, "该表没有签单或已竞价，不可拆分");
//            }
            } else {
                return new APPResultMessage(6001, "盲盒配包的订单，不可拆分");
            }
        } else {
            return new APPResultMessage(6001, "已经是子订单，不可拆分");
        }

        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage selectChild(int userId, Integer parentId) {
        List<TreeOrderListDTO> treeOrders = new ArrayList<>();
        buildTreeRecursively(parentId, treeOrders);
        if (treeOrders.isEmpty()) {
            return new APPResultMessage(6001, "该表单没有分表单");
        } else {
            ResultMessage resultMessage = ResultMessage.builder().setList(treeOrders);
            APPResultMessage<Object, ManagerOrderDTO> successMessage = APPResultMessage.getSuccessMessage();
            successMessage.setResult(resultMessage);
            return successMessage;
        }
    }

    private void buildTreeRecursively( Integer parentId, List<TreeOrderListDTO> treeOrders) {
        MjOrder parentOrder = orderMapper.selectByPrimaryKey(parentId);
        if (ObjUtil.isNotNull(parentOrder) && parentOrder.getIsHasChild() == 2) {
            //查找子表
            List<TreeOrderListDTO> childOrder = orderMapper.selectChildOrder(parentId);
            if (CollUtil.isNotEmpty(childOrder)){
                for (TreeOrderListDTO treeDTO : childOrder) {
                    if (ObjUtil.isNotNull(treeDTO)) {
                        treeDTO.setChildList(new ArrayList<>()); // 初始化子列表
                        treeOrders.add(treeDTO);
                        //循环查找子表
                        buildTreeRecursively(treeDTO.getId(), treeDTO.getChildList()); // 递归处理子节点
                    }
                }
            }
        }
    }

    public APPResultMessage deleteChild(Integer userId, Integer parentId) {
        MjOrder parenOrder = orderMapper.selectByPrimaryKey(parentId);
        List<TreeOrderListDTO> treeOrderListDTOS = orderMapper.selectChildOrder(parentId);
        if (CollUtil.isNotEmpty(treeOrderListDTOS)){
            orderMapper.updateStatusByParentId(parentId,(short) 10);
            orderMapper.updateIsHasChild(parentId,(short) 1);
            //父表单回到原来的状态
            orderMapper.updateStatusByOrderId(parentId,(short) 4);
            //开拓者和渠道回到原来的状态
            Set<Integer> allPushUserIds = getAllPushUserIds(parenOrder.getPushUserIds(), parenOrder.getNextPushUserIds(), parenOrder.getTransferUserIds(),parenOrder.getBiddingPushUserIds());
            for (Integer pushUserId : allPushUserIds) {
                MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, parentId);
                if (isHaveObj != null){
                    MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                    orderStatusObj.setOrderStatus(isHaveObj.getPreviousStatus() != null ? isHaveObj.getPreviousStatus() : (short) 85);
                    orderStatusObj.setUpdateTime(new Date());
                    orderStatusObj.setId(isHaveObj.getId());
                    mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                }
            }
            //渠道---已核价
            if (StringUtil.isNotBlank(parenOrder.getPushChannelUserIds())){
                for (String channelId : parenOrder.getPushChannelUserIds().split(",")) {
                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(channelId), parentId);
                    if (isHaveObj != null){
                        MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                        mjUserOrderStatus.setUpdateTime(new Date());
                        mjUserOrderStatus.setOrderStatus(isHaveObj.getPreviousStatus() != null ? isHaveObj.getPreviousStatus() : (short) 72);
                        mjUserOrderStatus.setPreviousStatus(isHaveObj.getPreviousStatus());
                        mjUserOrderStatus.setId(isHaveObj.getId());
                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                    }
                }
            }
            //记录操作日志
            logOperateMapper.addSelective(parenOrder.getProjectId(), parenOrder.getId(), userId,212,new Date(),3);
            return APPResultMessage.getSuccessMessage();
        } else {
            return new APPResultMessage(6001, "该表单没有分表单可以删除");
        }

    }

    public APPResultMessage confirmOrderUse(Integer userId, Integer orderId, Integer useType, BigDecimal expectPrice) {
        MjOrder mjOrder = orderMapper.selectByPrimaryKey(orderId);
        if ((ObjUtil.isNotNull(mjOrder.getOrderGo()) && mjOrder.getOrderGo() != 155) || ObjUtil.isNotNull(mjOrder.getExpectPrice())){
            return new APPResultMessage(6001, "该订单已进行了操作");
        }
        List<TreeOrderListDTO> treeOrderListDTOS = orderMapper.selectChildOrder(orderId);
        if (CollUtil.isNotEmpty(treeOrderListDTOS) ){
            return new APPResultMessage(6001, "该表单为父表单，不可操作");
        }
        if (useType == 155){
            orderMapper.updateOrderUseAndExpectPrice(orderId,useType,null);
        } else {
            //修改订单的用处和预计变现
            orderMapper.updateOrderUseAndExpectPrice(orderId,useType,expectPrice);
        }

        //订单状态改为已完成
        orderMapper.updateStatusByOrderId(orderId,(short) 7);
        orderMapper.updateEndTime(orderId,new Date());
        //开拓者为已结束状态
        Set<Integer> allPushUserIds = getAllPushUserIds(mjOrder.getPushUserIds(), mjOrder.getNextPushUserIds(), mjOrder.getTransferUserIds(),mjOrder.getBiddingPushUserIds());
        for (Integer pushUserId : allPushUserIds) {
            MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, mjOrder.getId());
            if (isHaveObj != null){
                MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                orderStatusObj.setOrderStatus(88);
                orderStatusObj.setUpdateTime(new Date());
                orderStatusObj.setId(isHaveObj.getId());
                mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
            }
        }
        //渠道为已结束状态
        if (StringUtil.isNotBlank(mjOrder.getPushChannelUserIds())){
            for (String channelId : mjOrder.getPushChannelUserIds().split(",")) {
                MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                mjUserOrderStatus.setOrderStatus(78);
                mjUserOrderStatus.setUpdateTime(new Date());
                MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(channelId), mjOrder.getId());
                if (isHaveObj != null){
                    mjUserOrderStatus.setId(isHaveObj.getId());
                    mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                }
            }
        }
        //记录操作日志
        logOperateMapper.addSelective(mjOrder.getProjectId(),orderId, userId,213,new Date(),3);
        return APPResultMessage.getSuccessMessage();

    }


    @Transactional
    public APPResultMessage doSplitOrderAfterBidding(int userId, Integer parentId, String orderStr, Integer fileType, String useTypeStr) {
        MjOrder parenOrder = orderMapper.selectByPrimaryKey(parentId);
        //已经是子订单的订单，新增的子订单归于父订单
        Integer allParentId = parentId;
        boolean isChildOrder = false; // 是否是子订单，false为否，true为是
        if (parenOrder.getParentId() != null) {
            // 如果进行的拆单是子订单
            allParentId = parenOrder.getParentId();
            isChildOrder = true;
        }
        //盲盒配包的订单，不可以拆单
        if (ObjUtil.isNotNull(parenOrder.getIsBlindBox()) && parenOrder.getIsBlindBox() == 1) {
            if (ObjUtil.isNotNull(fileType) && fileType == 1) {
                if (StrUtil.isNotBlank(orderStr) && StrUtil.isNotBlank(useTypeStr)) {
                    TreeMap<String, List<SplitGoodStrDTO>> orderMap = JSON.parseObject(orderStr, new TypeReference<TreeMap<String, List<SplitGoodStrDTO>>>() {
                    });
                    TreeMap<String, useTypeDTO> useTypeMap = JSON.parseObject(useTypeStr, new TypeReference<TreeMap<String, useTypeDTO>>() {
                    });
                    // 传的参数是一个Map的json对象，里面key为随意值，value为list<SplitGoodStrDTO>，SplitGoodStrDTO记录goodId,skuId,num
                    Integer splitTotalNum = 0;
                    //先遍历每个sku校验要拆单的商品数量和原表单商品数量是否一致
                    for (Map.Entry<String, List<SplitGoodStrDTO>> entry : orderMap.entrySet()) {
                        List<SplitGoodStrDTO> goodStrList = entry.getValue();
                        for (SplitGoodStrDTO strDTO : goodStrList) {
                            splitTotalNum = splitTotalNum + strDTO.getNum();
                        }
                    }
                    if (splitTotalNum > parenOrder.getTotalNum()) {
                        return new APPResultMessage(6001, "拆单商品总数量超过原表单数量");
                    } else if (splitTotalNum < parenOrder.getTotalNum()) {
                        return new APPResultMessage(6001, "拆单商品总数量小于原表单数量");
                    }
                    List<SplitGoodStrDTO> otherOrderGoodList = new ArrayList<>();
                    // 如果是子订单进行的拆掉，那么需要把传入的orderMap和useTypeMap的最后一条数据去除，因为是会对该子表单进行修改
                    if (isChildOrder){
                        String delOrderKey = "otherList";
                        otherOrderGoodList = orderMap.get(delOrderKey);
                        orderMap.remove(delOrderKey);
                        useTypeMap.remove(delOrderKey);
                    }
                    //遍历每个订单
                    for (Map.Entry<String, List<SplitGoodStrDTO>> entry : orderMap.entrySet()) {
                        List<SplitGoodStrDTO> goodStrList = entry.getValue();
                        if (goodStrList != null) {
                            //目标商品总价
                            BigDecimal targetGoodTotalPrice = BigDecimal.ZERO;
                            //目标商品实际成交总价
                            BigDecimal targetGoodRealTotalPrice = BigDecimal.ZERO;
                            //目标商品总数
                            Integer targetGoodTotalNum = 0;
                            //order
                            MjOrder targetOrder = new MjOrder();
                            targetOrder.setOrderKey(parenOrder.getOrderKey() + "-" + entry.getKey());
                            targetOrder.setCreateUserId(userId);
                            targetOrder.setCreateTime(new Date());
                            targetOrder.setUpdateTime(new Date());
                            targetOrder.setBrands(parenOrder.getBrands());
                            targetOrder.setCategoryId(parenOrder.getCategoryId());
                            targetOrder.setProjectId(parenOrder.getProjectId());
                            targetOrder.setIsPush(parenOrder.getIsPush());
                            targetOrder.setPushUserIds(parenOrder.getPushUserIds());
                            targetOrder.setIsNextPush((short) 1);
                            targetOrder.setNextPushUserIds(null);
                            targetOrder.setIsBlindBox((short) 1);
                            targetOrder.setIsBackPush((short) 1);
                            targetOrder.setFileType(fileType);
                            targetOrder.setIsTimeOut((short) 1);
                            targetOrder.setIsHasChild((short) 1);
                            targetOrder.setIsReset((short) 1);
                            targetOrder.setParentId(allParentId);
                            if (useTypeMap.containsKey(entry.getKey())) {
                                useTypeDTO useTypeDTO = useTypeMap.get(entry.getKey());
                                if (ObjUtil.isNotNull(useTypeDTO)) {
                                    targetOrder.setOrderGo(useTypeDTO.getUseType());
                                    if (useTypeDTO.getUseType() == 155) {
                                        targetOrder.setExpectPrice(null);
                                        targetOrder.setStatus((short) 4);
                                        if (ObjUtil.isNotNull(parenOrder.getCheckTime())) {
                                            targetOrder.setCheckTime(parenOrder.getCheckTime());
                                        }
                                        orderMapper.insertSelective(targetOrder);
                                        //开拓者为已签单状态
                                        Set<Integer> allPushUserIds = getAllPushUserIds(parenOrder.getPushUserIds(), parenOrder.getNextPushUserIds(), parenOrder.getTransferUserIds(), parenOrder.getBiddingPushUserIds());
                                        for (Integer pushUserId : allPushUserIds) {
                                            MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, targetOrder.getId());
                                            if (isHaveObj != null) {
                                                MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                                orderStatusObj.setOrderStatus(85);
                                                orderStatusObj.setUpdateTime(new Date());
                                                orderStatusObj.setId(isHaveObj.getId());
                                                mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                            } else {
                                                MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                                orderStatusObj.setUserId(pushUserId);
                                                orderStatusObj.setOrderId(targetOrder.getId());
                                                orderStatusObj.setOrderStatus(85);
                                                orderStatusObj.setCreateTime(new Date());
                                                orderStatusObj.setStatus((short) 1);
                                                orderStatusObj.setIsNextPush((short) 1);
                                                mjUserOrderStatusMapper.insertSelective(orderStatusObj);
                                            }
                                        }
                                    } else {
                                        targetOrder.setStatus((short) 7);
                                        targetOrder.setEndTime(new Date());
                                        if (ObjUtil.isNotNull(parenOrder.getCheckTime())) {
                                            targetOrder.setCheckTime(parenOrder.getCheckTime());
                                        }
                                        targetOrder.setExpectPrice(useTypeDTO.getExpectPrice());
                                        orderMapper.insertSelective(targetOrder);
                                        if (ObjUtil.isNotNull(targetOrder.getEndTime())) {
                                            //修改父订单结束时间
                                            orderMapper.updateEndTime(parenOrder.getId(), targetOrder.getEndTime());
                                        }
                                        //开拓者为已签单状态
                                        Set<Integer> allPushUserIds = getAllPushUserIds(parenOrder.getPushUserIds(), parenOrder.getNextPushUserIds(), parenOrder.getTransferUserIds(), parenOrder.getBiddingPushUserIds());
                                        for (Integer pushUserId : allPushUserIds) {
                                            MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, targetOrder.getId());
                                            if (isHaveObj != null) {
                                                MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                                orderStatusObj.setOrderStatus(88);
                                                orderStatusObj.setUpdateTime(new Date());
                                                orderStatusObj.setId(isHaveObj.getId());
                                                mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                            } else {
                                                MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                                orderStatusObj.setUserId(pushUserId);
                                                orderStatusObj.setOrderId(targetOrder.getId());
                                                orderStatusObj.setOrderStatus(88);
                                                orderStatusObj.setCreateTime(new Date());
                                                orderStatusObj.setStatus((short) 1);
                                                orderStatusObj.setIsNextPush((short) 1);
                                                mjUserOrderStatusMapper.insertSelective(orderStatusObj);
                                            }
                                        }
                                    }
                                }
                            }
                            //遍历每一个sku
                            for (SplitGoodStrDTO strDTO : goodStrList) {
                                if (ObjUtil.isNotNull(strDTO.getGoodId()) && strDTO.getNum() != 0) {
                                    //查找原表单的good
                                    MjGood oldGood = goodMapper.selectByPrimaryKey(strDTO.getGoodId());
                                    if (ObjUtil.isNotNull(strDTO.getSkuId())) {
                                        //查找原表单的sku
                                        MjGoodSku oldGoodSku = goodSkuMapper.selectByPrimaryKey(strDTO.getSkuId());
                                        if (strDTO.getNum() <= oldGoodSku.getGoodSkuNum()) {
                                            MjGood targetGood = new MjGood();
                                            targetGood.setGoodNum(strDTO.getNum());
                                            targetGood.setGoodName(oldGood.getGoodName());
                                            targetGood.setGoodExpirationDate(oldGood.getGoodExpirationDate());
                                            targetGood.setGoodWarrantyDate(oldGood.getGoodWarrantyDate());
                                            targetGood.setGoodOnlineLink(oldGood.getGoodOnlineLink());
                                            //价格就是总价=sku单价*数量
                                            targetGood.setGoodPrice(oldGoodSku.getGoodSkuPrice().multiply(new BigDecimal(strDTO.getNum())));
                                            targetGood.setGoodPic(oldGood.getGoodPic());
                                            targetGood.setGoodCategory(oldGood.getGoodCategory());
                                            targetGood.setGoodBoxNum(oldGood.getGoodBoxNum());
                                            targetGood.setGoodBoxSize(oldGood.getGoodBoxSize());
                                            targetGood.setGoodOneSize(oldGood.getGoodOneSize());
                                            targetGood.setShopFans(oldGood.getShopFans());
                                            targetGood.setGoodSaleNum(oldGood.getGoodSaleNum());
                                            //实际成交价也用sku的
                                            targetGood.setFinalPrice(oldGoodSku.getRealReadPrice() == null ? BigDecimal.ZERO : oldGoodSku.getRealReadPrice());
                                            targetGood.setCreateTime(new Date());
                                            targetGood.setStatus((short) 1);
                                            targetGood.setOrderId(targetOrder.getId());
                                            //价格就是总价=sku单价*数量
                                            targetGood.setGoodTotalPrice(oldGoodSku.getGoodSkuPrice().multiply(new BigDecimal(strDTO.getNum())));
                                            goodMapper.insertSelective(targetGood);
                                            //sku
                                            MjGoodSku targetGoodSku = new MjGoodSku();
                                            targetGoodSku.setGoodSkuNum(strDTO.getNum());
                                            targetGoodSku.setGoodSkuPic(oldGoodSku.getGoodSkuPic());
                                            targetGoodSku.setGoodSkuPrice(oldGoodSku.getGoodSkuPrice());
                                            targetGoodSku.setGoodSku(oldGoodSku.getGoodSku());
                                            targetGoodSku.setGoodId(targetGood.getId());
                                            targetGoodSku.setCreateTime(new Date());
                                            targetGoodSku.setStatus((short) 1);
                                            targetGoodSku.setRealReadPrice(oldGoodSku.getRealReadPrice() == null ? BigDecimal.ZERO : oldGoodSku.getRealReadPrice());
                                            targetGoodSku.setGoodSkuTotalPrice(oldGoodSku.getGoodSkuPrice().multiply(new BigDecimal(strDTO.getNum())));
                                            goodSkuMapper.insertSelective(targetGoodSku);

                                            targetGoodTotalPrice = targetGoodTotalPrice.add(oldGoodSku.getGoodSkuPrice().multiply(new BigDecimal(strDTO.getNum())));
                                            targetGoodRealTotalPrice = targetGoodRealTotalPrice.add(oldGoodSku.getRealReadPrice() == null ? BigDecimal.ZERO : oldGoodSku.getRealReadPrice().multiply(new BigDecimal(strDTO.getNum())));
                                            targetGoodTotalNum = targetGoodTotalNum + strDTO.getNum();

                                        } else {
                                            return new APPResultMessage(6001, "拆单商品: " + oldGood.getGoodName() + " 数量超过原表单数量");
                                        }
                                    }
                                }
                            }
                            orderMapper.updateNumAndPriceByOrderId(targetOrder.getId(), targetGoodTotalNum, targetGoodTotalPrice, targetGoodRealTotalPrice);
                        }
                    }
                    // 如果当前的订单是对子订单进行的拆单，那么需要把原有的数据进行修改
                    if (isChildOrder){
                        Map<Integer, Integer> goodNumMap = new HashMap<Integer, Integer>();
                        for (SplitGoodStrDTO dto : otherOrderGoodList){
                            // 修改渠道核价竞价的商品数量
                            userOrderGoodMapper.updateNumByGoodIdAndSkuId(dto.getGoodId(), dto.getSkuId(), dto.getNum());
                            // 修改订单对应的商品数量
                            goodSkuMapper.updateNumByGoodIdAndSkuId(dto.getGoodId(), dto.getSkuId(), dto.getNum());
                            if (goodNumMap.containsKey(dto.getGoodId())){
                                goodNumMap.put(dto.getGoodId(), goodNumMap.get(dto.getGoodId()) + dto.getNum());
                            }else {
                                goodNumMap.put(dto.getGoodId(), dto.getNum());
                            }
                        }
                        for (Integer goodId : goodNumMap.keySet()){
                            goodMapper.updateNumByGoodId(goodId, goodNumMap.get(goodId));
                        }
                        BigDecimal totalPrice = goodMapper.selectTotalPriceByOrderId(parentId);
                        orderMapper.updateTotalPriceByOrderId(parentId, totalPrice);
                    }
                    // 如果父订单有成本或者内部货值，那么把子订单对应的成本或者内部货值算出来
                    doCountSubOrder(allParentId);
                } else {
                    return new APPResultMessage(6001, "订单列表缺失");
                }
                orderMapper.updateIsHasChild(parentId, (short) 2);
                if (allParentId != null){
                    orderMapper.updateIsHasChild(allParentId, (short) 2);
                }
            } else {
                return new APPResultMessage(6001, "非易货订单，不可拆分");
            }
        } else {
            return new APPResultMessage(6001, "盲盒配包的订单，不可拆分");
        }
        return APPResultMessage.getSuccessMessage();
    }

    // allParentId为父订单id
    public void doCountSubOrder(Integer allParentId){
        // 计算子订单中所对应的成本和内部货值
        MjOrder mjOrder = orderMapper.selectByPrimaryKey(allParentId);
        if (mjOrder != null){
            BigDecimal totalPrice = mjOrder.getTotalPrice();
            // 判断预估成本
            boolean estimatedCostType = false;
            if (mjOrder.getEstimatedCost() != null && mjOrder.getEstimatedCost().compareTo(BigDecimal.ZERO) > 0){
                estimatedCostType = true;
            }
            // 判断预估-自营媒体成本
            boolean estimatedSelfMediaCostType = false;
            if (mjOrder.getEstimatedSelfMediaCost() != null && mjOrder.getEstimatedSelfMediaCost().compareTo(BigDecimal.ZERO) > 0){
                estimatedSelfMediaCostType = true;
            }
            // 判断预估-外采媒体成本
            boolean estimatedExternalMediaCostType = false;
            if (mjOrder.getEstimatedExternalMediaCost() != null && mjOrder.getEstimatedExternalMediaCost().compareTo(BigDecimal.ZERO) > 0){
                estimatedExternalMediaCostType = true;
            }
            // 判断实际成本
            boolean actualCostType = false;
            if (mjOrder.getActualCost() != null && mjOrder.getActualCost().compareTo(BigDecimal.ZERO) > 0){
                actualCostType = true;
            }
            // 判断实际-自营媒体成本
            boolean actualSelfMediaCostType = false;
            if (mjOrder.getActualSelfMediaCost() != null && mjOrder.getActualSelfMediaCost().compareTo(BigDecimal.ZERO) > 0){
                actualSelfMediaCostType = true;
            }
            // 判断实际-外采媒体成本
            boolean actualExternalMediaCostType = false;
            if (mjOrder.getActualExternalMediaCost() != null && mjOrder.getActualExternalMediaCost().compareTo(BigDecimal.ZERO) > 0){
                actualExternalMediaCostType = true;
            }
            // 判断内部货值
            boolean innerPriceType = false; // 判断是否进行内部货值计算
            if (mjOrder.getInnerPrice() != null && mjOrder.getInnerPrice().compareTo(BigDecimal.ZERO) > 0){
                innerPriceType = true;
            }
            if (innerPriceType ||
                    estimatedCostType || estimatedSelfMediaCostType || estimatedExternalMediaCostType ||
                    actualCostType || actualSelfMediaCostType || actualExternalMediaCostType){
                List<TreeOrderListDTO> treeOrderListDTOS = orderMapper.selectChildOrder(allParentId);
                for (TreeOrderListDTO dto : treeOrderListDTOS){
                    BigDecimal divideTotalPrice = dto.getTotalPrice().divide(totalPrice, 6, BigDecimal.ROUND_HALF_UP);
                    if (estimatedCostType){
                        dto.setEstimatedCost(mjOrder.getEstimatedCost().multiply(divideTotalPrice).setScale(2, BigDecimal.ROUND_HALF_UP));
                    }
                    if (estimatedSelfMediaCostType){
                        dto.setEstimatedSelfMediaCost(mjOrder.getEstimatedSelfMediaCost().multiply(divideTotalPrice).setScale(2, BigDecimal.ROUND_HALF_UP));
                    }
                    if (estimatedExternalMediaCostType){
                        dto.setEstimatedExternalMediaCost(mjOrder.getEstimatedExternalMediaCost().multiply(divideTotalPrice).setScale(2, BigDecimal.ROUND_HALF_UP));
                    }
                    if (actualCostType){
                        // 计算成本，子订单成本 = 子订单的总货值 / 父订单的总货值 * 成本
                        dto.setActualCost(mjOrder.getActualCost().multiply(divideTotalPrice).setScale(2, BigDecimal.ROUND_HALF_UP));
                    }
                    if (actualSelfMediaCostType){
                        dto.setActualSelfMediaCost(mjOrder.getActualSelfMediaCost().multiply(divideTotalPrice).setScale(2, BigDecimal.ROUND_HALF_UP));
                    }
                    if (actualExternalMediaCostType){
                        dto.setActualExternalMediaCost(mjOrder.getActualExternalMediaCost().multiply(divideTotalPrice).setScale(2, BigDecimal.ROUND_HALF_UP));
                    }
                    if (innerPriceType){
                        // 计算内部货值，子订单内部货值 = 子订单的总货值 / 父订单的总货值 * 内部货值
                        dto.setInnerPrice(mjOrder.getInnerPrice().multiply(divideTotalPrice).setScale(2, BigDecimal.ROUND_HALF_UP));
                    }
                    orderMapper.updateInnerPriceAndActualCostById(dto.getId(), dto.getInnerPrice(),
                            dto.getActualCost(), dto.getActualSelfMediaCost(), dto.getActualExternalMediaCost(),
                            dto.getEstimatedCost(), dto.getEstimatedSelfMediaCost(), dto.getEstimatedExternalMediaCost());
                }
            }
        }
    }


    public APPResultMessage doSetOrderRate(int userId, short userType, Integer orderId, Integer rateId) {
        String key = "doSetOrderRate_" + orderId;
        String requestId = UUID.randomUUID().toString();
        boolean flag = LockUtil.tryGetDistributedLock(key, requestId);
        if (flag){
            MjOrderOtherSetting otherSetting = orderOtherSettingMapper.selectMsgByOrderId(orderId);
            if (otherSetting == null){
                MjOrderOtherSetting setting = new MjOrderOtherSetting();
                setting.setOrderId(orderId);
                setting.setRateId(rateId);
                orderOtherSettingMapper.insertSelective(setting);
            }else {
                orderOtherSettingMapper.updateRateByOrderId(orderId, rateId);
            }
            // 添加修改记录
            MjOrderRateRecord record = new MjOrderRateRecord();
            record.setOrderId(orderId);
            record.setUserType(userType);
            record.setUserId(userId);
            record.setRateId(rateId);
            record.setCreateTime(new Date());
            orderRateRecordMapper.insertSelective(record);
            LockUtil.releaseDistributedLock(key, requestId);
            return APPResultMessage.getSuccessMessage();
        }else {
            return APPResultMessage.getErrorMessage("有账户在提交评级，请稍后重新提交");
        }
    }

    public APPResultMessage getSetOrderRateRecordList(Integer orderId) {
        List<MjOrderRateRecordDTO> dtoList = orderRateRecordMapper.selectRecordListByOrderId(orderId);
        for (MjOrderRateRecordDTO dto : dtoList){
            if (dto.getUserType() == 1){
                dto.setUsername(normalUserMapper.selectByPrimaryKey(dto.getUserId()).getNickName());
            }else {
                dto.setUsername(managerUserMapper.selectByPrimaryKey(dto.getUserId()).getUsername());
            }
        }
        APPResultMessage message = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setList(dtoList);
        message.setResult(resultMessage);
        return message;
    }

    public APPResultMessage doSkipBidding(Integer orderId, Integer userId, Integer chooseOrderId) {
        if (chooseOrderId == null){
            return new APPResultMessage(6001, "请选择对应的表单");
        }
        MjOrder mjOrder = orderMapper.selectByPrimaryKey(orderId);
        //订单状态改为已完成
        orderMapper.updateStatusByOrderId(orderId,(short) 7);
        orderMapper.updateEndTime(orderId,new Date());
        MjOrder chooseOrder = orderMapper.selectByPrimaryKey(chooseOrderId);
        if (chooseOrder != null){
            // 把原表单里的推送的开拓者提取出来
            Set<Integer> allPushUserIds = getAllPushUserIds(chooseOrder.getPushUserIds(), chooseOrder.getNextPushUserIds(), chooseOrder.getTransferUserIds(), chooseOrder.getBiddingPushUserIds());
            if (allPushUserIds != null && !allPushUserIds.isEmpty()){
                for (Integer pushUserId : allPushUserIds) {
                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, orderId);
                    if (isHaveObj == null){
                        MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                        orderStatusObj.setUserId(pushUserId);
                        orderStatusObj.setOrderId(orderId);
                        orderStatusObj.setOrderStatus(88);
                        orderStatusObj.setStatus((short) 1);
                        orderStatusObj.setCreateTime(new Date());
                        orderStatusObj.setIsNextPush((short) 1);
                        mjUserOrderStatusMapper.insertSelective(orderStatusObj);
                    }else {
                        mjUserOrderStatusMapper.updateOrderStatusById(isHaveObj.getId(), 88);
                    }
                }
            }
            MjNormalUser normalUser = normalUserMapper.selectByPrimaryKey(chooseOrder.getLastUserId());
            Integer pushUserId = normalUser.getPushUserId();
            orderMapper.updateLastUserIdById(orderId, normalUser.getId());
            // 修改已中标的渠道商所对应的开拓者的状态
            MjUserOrderStatus userOrderStatus = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, orderId);
            if (userOrderStatus == null){
                MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                orderStatusObj.setUserId(pushUserId);
                orderStatusObj.setOrderId(orderId);
                orderStatusObj.setOrderStatus(99);
                orderStatusObj.setStatus((short) 1);
                orderStatusObj.setCreateTime(new Date());
                orderStatusObj.setIsNextPush((short) 1);
                mjUserOrderStatusMapper.insertSelective(orderStatusObj);
            }else {
                userOrderStatus.setOrderStatus(99);
                userOrderStatus.setUpdateTime(new Date());
                mjUserOrderStatusMapper.updateByPrimaryKeySelective(userOrderStatus);
            }
        }
        //记录操作日志
        logOperateMapper.addSelective(mjOrder.getProjectId(),orderId, userId,217,new Date(),3);
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage getOtherHasBiddingOrderList(Integer orderId) {
        MjOrder order = orderMapper.selectByPrimaryKey(orderId);
        List<OrderBriefDTO> list = orderMapper.selectBriefHasBiddingListByProjectIdAndNoOrderId(order.getProjectId(), orderId);
        APPResultMessage message = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setList(list);
        message.setResult(resultMessage);
        return message;
    }

    public APPResultMessage doSubmitFlagshipStoreData(FlagshipStoreDataReq req, int userId, short userType) {
        if (req.getOrderId() == null){
            return new APPResultMessage(6001, "无订单");
        }
        if (StringUtil.isBlank(req.getSkuData())){
            return new APPResultMessage(6001, "无商品");
        }
        List<FlagshipStoreDataReq.SkuData> skuDataList = JSON.parseArray(req.getSkuData(), FlagshipStoreDataReq.SkuData.class);
        if (skuDataList.isEmpty()){
            return new APPResultMessage(6001, "暂无数据");
        }
        int totalSize = skuDataList.size();
        MjOrder dto = orderMapper.selectByPrimaryKey(req.getOrderId());
        // 对skuDataList的长度进行处理，超过100另起一次修改sql
        int loopCount = (int) Math.ceil(totalSize / 100.0);
        for (int i = 0; i < loopCount; i++) {
            // 计算当前批次的起始索引
            int start = i * 100;
            // 计算当前批次的结束索引（避免最后一批越界）
            int end = Math.min((i + 1) * 100, totalSize);
            // 截取当前批次的子列表（注意：subList返回的是原列表的视图，不建议修改）
            List<FlagshipStoreDataReq.SkuData> batchList = skuDataList.subList(start, end);
            // 调用mapper更新当前批次
            if (dto.getFileType() != null){
                if (dto.getFileType() == 2){
                    orderLocalLifeMapper.updateFlagshipStoreData(req.getOrderId(), batchList);
                }else {
                    goodSkuMapper.updateFlagshipStoreData(req.getOrderId(), batchList);
                }
            }
        }
        BigDecimal goodRealTotalPrice = BigDecimal.ZERO;
        for (FlagshipStoreDataReq.SkuData skuData : skuDataList){
            BigDecimal oneFinalTotalPrice = skuData.getFinalPrice().multiply(BigDecimal.valueOf(skuData.getNum()));
            goodRealTotalPrice = goodRealTotalPrice.add(oneFinalTotalPrice);
        }
        orderMapper.updateRealTotalPriceById(req.getOrderId(), goodRealTotalPrice);
        MjOrder order = orderMapper.selectByPrimaryKey(req.getOrderId());
        // 通知
        Map<String, Object> templateParams = new HashMap<>();
        notifyService.doSendNotifyByRoleId(userId, userType, "submitRealPrice", templateParams, order.getProjectId());
        return APPResultMessage.getSuccessMessage();
    }

    public APPResultMessage viewGoodsList(OrderIdReq req) {
        List<?> list = new ArrayList<>();
        MjOrder dto = orderMapper.selectByPrimaryKey(req.getOrderId());
        if (dto.getFileType() != null){
            if (dto.getFileType() == 2){
                List<MjOrderLocalLife> goodListDTOS = orderLocalLifeMapper.selectListByOrderId(dto.getId());
                list = goodListDTOS;
            } else if (dto.getFileType() == 3){
                List<MjOrderHotel> goodListDTOS = mjOrderHotelMapper.selectListByOrderId(dto.getId());
                list = goodListDTOS;
            }else {
                List<GoodListDTO> goodListDTOS = goodSkuMapper.selectListByOrderId(dto.getId());
                list = goodListDTOS;
            }
        }
        APPResultMessage message = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setList(list);
        message.setResult(resultMessage);
        return message;
    }
}
